Decouple an abstraction from its implementation allowing the two to vary independently.
将一个抽象与实现解耦,以便两者可以独立的变化。
interface IDrawingApi {
void DrawCircle(double x, double y, double radius);
}
class DrawingApi1 : IDrawingApi {
public void DrawCircle(double x, double y, double radius) {
Console.WriteLine("API1.circle at {0},{1} radius {2}", x, y, radius);
}
}
class DrawingApi2 : IDrawingApi {
public void DrawCircle(double x, double y, double radius) {
Console.WriteLine("API2.circle at {0},{1} radius {2}", x, y, radius);
}
}
abstract class Shape {
protected IDrawingApi DrawingApi;
protected Shape(IDrawingApi drawingApi) {
this.DrawingApi = drawingApi;
}
public abstract void Draw();
public abstract void ResizeByPercent(double percent);
}
class CircleShape : Shape {
private readonly double _x;
private readonly double _y;
private double _radius;
public CircleShape(double x, double y, double radius, IDrawingApi drawingApi)
: base(drawingApi) {
this._x = x;
this._y = y;
this._radius = radius;
}
public override void Draw() {
this.DrawingApi.DrawCircle(this._x, this._y, this._radius);
}
public override void ResizeByPercent(double percent) {
this._radius *= percent;
}
}
class Program {
static void Main(string[] args) {
var shapes = new Shape[] {
new CircleShape(1, 2, 3, new DrawingApi1()),
new CircleShape(5, 7, 11, new DrawingApi2()),
};
foreach (var shape in shapes) {
shape.ResizeByPercent(2.5);
shape.Draw();
}
Console.ReadKey();
}
}