解释器模式、享元模式、桥梁模式
解释器模式
给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子
享元模式
定义
使用共享对象可有效地支持大量的细粒度的对象
代码
抽象的享元角色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public abstract class Flyweight {
private String intrinsic;
protected final String Extrinsic;
public Flyweight(String extrinsic) { Extrinsic = extrinsic; }
public abstract void operate();
public String getIntrinsic() { return intrinsic; }
public void setIntrinsic(String intrinsic) { this.intrinsic = intrinsic; } }
|
享元的具体实现
1 2 3 4 5 6 7 8 9 10 11
| public class ConcreteFlyweight1 extends Flyweight {
public ConcreteFlyweight1(String extrinsic) { super(extrinsic); }
@Override public void operate() { System.out.println("concrete flyweight 1"); } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class ConcreteFlyweight2 extends Flyweight {
public ConcreteFlyweight2(String extrinsic) { super(extrinsic); }
@Override public void operate() { System.out.println("concrete flyweight 2"); } }
|
工厂类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class FlyweightFactory {
private static HashMap<String,Flyweight> pool = new HashMap<>();
public static Flyweight getFlyweight(String extrinsic){ Flyweight flyweight = null; if(pool.containsKey(extrinsic)){ flyweight = pool.get(extrinsic); }else{ flyweight = new ConcreteFlyweight1(extrinsic); pool.put(extrinsic,flyweight); } return flyweight; }
}
|
桥梁角色
定义
将抽象和实现解耦,使得两者可以独立的变化
代码
接口角色
1 2 3 4
| public interface Implementor { void doSomething(); void doAnything(); }
|
接口的实现
1 2 3 4 5 6 7 8 9 10 11 12
| public class ConcreteImpletor1 implements Implementor {
@Override public void doSomething() { System.out.println("something 1"); }
@Override public void doAnything() { System.out.println("anything 1"); } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class ConcreteImpletor2 implements Implementor { @Override public void doSomething() { System.out.println("something 2"); }
@Override public void doAnything() { System.out.println("anything 2"); } }
|
调用抽象角色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public abstract class Abstraction {
private Implementor implementor;
public Abstraction(Implementor implementor) { this.implementor = implementor; }
public void request(){ this.implementor.doSomething(); }
public Implementor getImplementor() { return implementor; } }
|
调用角色
1 2 3 4 5 6 7 8 9 10 11 12
| public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) { super(implementor); }
@Override public void request() { super.request(); super.getImplementor().doAnything(); } }
|
测试
1 2 3 4 5 6 7 8 9 10
| public class RefinedAbstractionTest {
@Test public void testAbstraction(){ Implementor implementor = new ConcreteImpletor1(); Abstraction abstraction = new RefinedAbstraction(implementor); abstraction.request(); }
}
|