public interface State{ public void des(); public void action(); } public class State1 implements State{ Sys sys; public Sate1(Sys s) { this.sys=sys; } public void des(){ .../ implements } public void action(){ .../ change the state sys.setState(s.getState2()); } } public class State2 implements State{ Sys sys; public Sate2(Sys s) { this.sys=sys; } public void des(){ .../ implements } public void action(){ .../ change the state sys.setState(s.getState1()); } } public class Sys { private State1 state1; private State2 state2; private State state;//record the system's state ....//state1 & state2's setter & getter public Sys(State state) { this.state=state; } public void setState(State state) { this.state=state; } public void aciton() { state.action(); } }
public classItem{ .....//各种属性 } public class Set1{ item[] items; ... public Iterator createIterator(){ return new ItemIterator(items); } } public class Set2{ ArrayList items; ... public Iterator createIterator(){ return items.iterator(); } } public class ItemIterator implements Iterator{ Item[] items; int position; public ItemIterator(Item[] items) { this.items=items; position=0; } public Object next() { Item i=items[position]; position=position+1; return i; } public boolean hasNext() { if (position>=items.lenght || items[position]==null) return false; else return true; } }
public abstract class CAL{ public final void algorithm() { A1(); A2(); if (Judge()) A3(); A4(); } public void A1(){ //实现 ..... } public void A2(){ //实现 ..... } public abstract void A3(){} public abstract void A4(){} public boolean Judge(){ return true; } }
public interface IInterface1(){ public void method1(); } public interface IInterface2(){ public void method2(); } public class adapter implements IInterface1{ IInterface2 v; public adapter(IInterface2 t){ this.v=t; } public void method1(){ v.method2(); } }
现在我们调用IIterface2的method1的方法的时候,就是可以直接构造一个适配器来完成
1 2 3 4 5 6 7 8 9 10 11 12
public class A{
public void method3(IInterface1 t) { t.method1(); }
public static void main(String[] arg) { (new A()).method3(new adapter(claimplementInterfce2)); } }
public class WearShoe implements Wear{ public void excute() { .....//穿鞋的动作 } } public class WearShirt implements Wear{ public void excute() { .....//穿衬衫的动作 } } public class WearPants implements Wear{ public void excute() { .....//穿裤子的动作 } }
public class decorator1 extends BaseClass{ BaseClass baseClass; public decorator1(BaseClass t) { this.baseClass = t; } public string who() { return baseClass.who()+",decoratro1"; } public int cost() { return baseClass.cost()+10; } } public class decorator2 extends BaseClass{ BaseClass baseClass; public decorator2(BaseClass t) { this.baseClass = t; } public string who() { return baseClass.who()+",decoratro2"; } public int cost() { return baseClass.cost()+20; } }
然后我们在用decorator1 和decorator2 来装饰A的时候,就有了很犀利的调用方法:
1 2 3 4 5
A a; a=new decorator1(a); a=new deocorator2(a); system.out.println(a.who()); system.out.println(a.cost());