7) Bridge Pattern
类别:
Structural Patterns
问题:
连连看的问题
不使用桥接,要写81 个类,使用桥接,只需要18个类
方案:
示例:
public class BridgePatternDemo { public static void main(String[] args) { Somebody sb = new Xiaohong(new Banana()); sb.eat(); sb = new Liming(new Apple()); sb.eat(); } } interface Something { public String getName(); } class Apple implements Something { public String getName() { return "apple"; } } class Banana implements Something { public String getName() { return "banana"; } } abstract class Somebody { protected Something something; public Somebody(Something something) { this.something = something; } abstract public void eat(); } class Xiaohong extends Somebody { public Xiaohong(Something something) { super(something); } @Override public void eat() { System.out.println("Xiaohong eat " + something.getName()); } } class Liming extends Somebody { public Liming(Something something) { super(something); } @Override public void eat() { System.out.println("Liming eat " + something.getName()); } }
Xiaohong eat banana Liming eat apple
应用:
不足:(
优化:)