意图:将抽象部分与实现部分分离,使它们都可以独立的变化。
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。
如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
python实现
from abc import ABCMeta,abstractmethod
class Shape(metaclass=ABCMeta):
def __init__(self,color):
self.color = color
@abstractmethod
def draw(self):
pass
class Color(metaclass=ABCMeta):
@abstractmethod
def paint(self,shape):
pass
class Rectangle(Shape):
name = "长方形"
def draw(self):
self.color.paint(self)
class Circle(Shape):
name = "圆形"
def draw(self):
self.color.paint(self)
class Red(Color):
def paint(self,shape):
print(f"红色的{shape.name}")
class Green(Color):
def paint(self,shape):
print(f"绿色的{shape.name}")
obj = Rectangle(Green())
obj.draw()
dart 实现
abstract class DrawAPI {
void drawCircle(int radius, int x, int y);
}
class RedCircle implements DrawAPI {
@override
void drawCircle(int radius, int x, int y) {
print("Drawing Circle[ color: red, radius: $radius"
", x: $x, y:$y]");
}
}
class GreenCircle implements DrawAPI {
@override
void drawCircle(int radius, int x, int y) {
print("Drawing Circle[ color: green, radius: $radius"
", x: $x, y:$y]");
}
}
abstract class Shape {
DrawAPI _drawAPI;
Shape(this._drawAPI);
void draw();
}
class Circle extends Shape {
late int _x, _y, _radius;
Circle(this._x, this._y, this._radius, DrawAPI drawAPI) : super(drawAPI);
@override
void draw() {
_drawAPI.drawCircle(_radius, _x, _y);
}
}
void main(List<String> args) {
Shape redCircle = Circle(100, 100, 10, RedCircle());
Shape greenCircle = Circle(100, 100, 10, GreenCircle());
redCircle.draw();
greenCircle.draw();
}