
GoF Definition:
Decouple an abstraction from its implementation so that the two can vary independently.
概念
把事物对象和其具体行为特征分离开,使其可以独立变化。
例子
在一般的软件公司里,技术支持起到了研发团队和客户之间的桥接作用。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
public interface { void fillWithColor(int border); }
public class GreenColor implements { public void fillWithColor(int border) { System.out.println("Green Color with " + border + " inch border"); } }
public class RedColor implements { public void fillWithColor(int border) { System.out.println("Red color with " + border + " inch border"); } }
public abstract class Shape { protected IColor color;
protected Shape(IColor c) { this.color = c; }
abstract void drawShape(int border);
abstract void modifyBorder(int border, int increment); }
public class Rectangle extends Shape { protected Rectangle(IColor c) { super(c); }
void drawShape(int border) { System.out.println("This Rectangle is colored with: "); color.fillWithColor(border); }
void modifyBorder(int border, int increment) { System.out.println("nNow we are changing the border length " + increment + "times"); border = border * increment; drawShape(border); } }
public class Triangle extends Shape { protected Triangle(IColor c) { super(c); }
void drawShape(int border) { System.out.println("This Triangle is colored with:"); color.fillWithColor(border); }
@Override void modifyBorder(int border, int increment) { System.out.println("nNow we are changing the border length " + increment + "times"); border = border * increment; drawShape(border); } }
|
近期评论