public class Context { private State state; public Context(State state) { this.state = state; } public State getState() { return state; } public void setState(State state) { this.state = state; } public void request() { this.state.handle(this); } }
//抽象狀態類 public abstract class State { public abstract void handle(Context context); }
//具體狀態類A class ConcreteStateA extends State { public void handle(Context context) { System.out.println(“現在是在狀態A”); context.setState(new ConcreteStateB()); } }//具體狀態類B class ConcreteStateB extends State { public void handle(Context context) { System.out.println(“現在是在狀態B”); context.setState(new ConcreteStateC()); } }//具體狀態類C class ConcreteStateC extends State { public void handle(Context context) { System.out.println(“現在是在狀態C”); context.setState(new ConcreteStateA()); } }
//客戶端:不斷請求,不斷更改狀態 public class StateClient { public static void main(String[] args) { Context context = new Context(new ConcreteStateA()); context.request(); context.request(); context.request(); context.request(); context.request(); } } 輸出: 現在是在狀態A 現在是在狀態B 現在是在狀態C 現在是在狀態A 現在是在狀態B
//備忘錄(Memento)類
public class Memento {
private String state;
public Memento(String state) {this.state = state;}
public String getState() {return state;}
public void setState(String state) {this.state = state;}
}
//管理者(CareTaker)類:管理備忘錄
public class CareTaker {
private Memento memento;
public Memento getMemento() { return memento; }
public void setMemento(Memento memento) { this.memento = memento; }
}
//發起人(Originator) 類
public class Originator {
private String state;
public Memento createMemento() { return new Memento(this.state);}
public void recoverMemento(Memento memento) { this.setState(memento.getState()); }
public void show() {System.out.println("state = " this.state); }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
}
//客戶端
public class MementoClient {
public static void main(String[] args) {
// 設定初始狀態
Originator originator = new Originator();
originator.setState("On");
originator.show();
// 管理者通過備忘錄儲存狀態,由於有了很好地封裝,可以隱藏Originator的實現細節
CareTaker careTaker = new CareTaker();
careTaker.setMemento(originator.createMemento());
// 改變狀態
originator.setState("Off");
originator.show();
// 通過管理者從備忘錄中恢復狀態
originator.recoverMemento(careTaker.getMemento());
originator.show();
}
}
輸出:
state = On
state = Off
state = On
//Component為組合中的物件宣告介面,在適當情況下,實現所有類共有介面的預設行為。 public abstract class Component { protected String name; public Component(String name) { this.name = name; } public abstract void add(Component component); public abstract void remove(Component component); public abstract void display(int depth); }
//Leaf在組合中表示葉節點物件,葉節點沒有子節點,實際上它的add、remove方法都是多餘的,實際上我覺得這裡有點違反了介面隔離原則:每個介面中不存在子類用不到卻必須實現的方法,也就是Component介面存在子類Leaf用不上卻必須實現的方法 public class Leaf extends Component { public Leaf(String name) { super(name); } public void add(Component component) { System.out.println(“cannot add to a leaf”); } public void remove(Component component) { System.out.println(“cannot remove from a leaf”); } public void display(int depth) { // 通過“-”的數目顯示級別 System.out.println(StringUtil.repeatableString(“-“, depth) this.name); } }
//定義有枝節點行為,用來儲存子部件 public class Composite extends Component { private List<Component> children = new ArrayList<Component>(); public Composite(String name) { super(name); } public void add(Component component) { children.add(component); } public void remove(Component component) { children.remove(component); } public void display(int depth) { // 顯示其枝節點名稱,並對其下級進行遍歷 System.out.println(StringUtil.repeatableString(“-“, depth) this.name); for (Component component : children) { component.display(depth 2); } } }
//客戶端。通過Component介面操作組合部件的物件 public class CompositeClient { public static void main(String[] args) { // 生成樹根,根上長出兩葉Leaf A和Leaf B Composite root = new Composite(“root”); root.add(new Leaf(“Leaf A”)); root.add(new Leaf(“Leaf B”)); // 根上長出分支Composite X,分支上也有兩葉Leaf X-A和Leaf X-B Composite compositeX = new Composite(“Composite X”); compositeX.add(new Leaf(“Leaf X-A”)); compositeX.add(new Leaf(“Leaf X-B”)); root.add(compositeX); // 在Composite X上再長出分支Composite X-Y,分支上也有兩葉Leaf X-Y-A和Leaf X-Y-B Composite compositeXY = new Composite(“Composite X-Y”); compositeXY.add(new Leaf(“Leaf X-Y-A”)); compositeXY.add(new Leaf(“Leaf X-Y-B”)); compositeX.add(compositeXY); // 顯示大樹的樣子 root.display(1); } }
列印出: -root —Leaf A —Leaf B —Composite X —–Leaf X-A —–Leaf X-B —–Composite X-Y ——-Leaf X-Y-A ——-Leaf X-Y-B
//聚集介面,可以理解為Iterable public interface Aggregate<T> { public Iterator<T> createIterator(); }
//具體聚集類 public class ConcreteAggregate<T> implements Aggregate<T> { private List<T> items = new ArrayList<T>(); @Override public Iterator<T> createIterator() { return new ConcreteIterator<T>(this); } public int count() { return items.size(); } public T getItems(int index) { return items.get(index); } public void setItems(T item) { items.add(item); } }
//迭代器介面 public interface Iterator<T> { public T first(); public T next(); public boolean isDone(); public T currentItem(); }
//具體迭代器類,給出一種具體迭代的實現方式。思考:迭代器表示的是一種迭代的行為,而聚集則是真正要被迭代的資料集合。之所以要將迭代器和聚集分開,就是為了將行為與資料分開。 可類比Java中Iterator與Iterable的關係進行理解 public class ConcreteIterator<T> implements Iterator<T> { private ConcreteAggregate<T> concreteAggregate; private int current = 0; public ConcreteIterator(ConcreteAggregate<T> concreteAggregate) {
this.setConcreteAggregate(concreteAggregate);
} @Override public T first() { return concreteAggregate.getItems(0); } @Override public T next() { current ; if (current < concreteAggregate.count()) { return concreteAggregate.getItems(current); } return null; } @Override public boolean isDone() {
return current >= concreteAggregate.count() ? true : false;
} @Override public T currentItem() { return concreteAggregate.getItems(current); } public ConcreteAggregate<T> getConcreteAggregate() { return concreteAggregate; } public void setConcreteAggregate(ConcreteAggregate<T> concreteAggregate) {
this.concreteAggregate = concreteAggregate;
} public int getCurrent() { return current; } public void setCurrent(int current) { this.current = current; } }
//迭代器客戶端 public class IteratorClient { public static void main(String[] args) { ConcreteAggregate<String> bus = new ConcreteAggregate<String>(); bus.setItems(“大鳥”); bus.setItems(“小菜”); bus.setItems(“行李”); bus.setItems(“老外”); bus.setItems(“公交內部員工”); bus.setItems(“小偷”); Iterator<String> iterator = new ConcreteIterator<String>(bus); while (!iterator.isDone()) { System.out.println(iterator.currentItem() “請買票!”); iterator.next(); } } } 輸出: 大鳥請買票! 小菜請買票! 行李請買票! 老外請買票! 公交內部員工請買票! 小偷請買票!
//知道如何實施與執行一個與請求相關的操作,任何類都可能作為一個接收者。真正執行請求的地方!
interface Reciever { //比喻為廚師
public void action();
}
class RecieverA implements Reciever { //烤肉的廚師
@Override
public void action() {
System.out.println("RecieverA執行請求!");
}
}
class RecieverB implements Reciever { //炒菜的廚師
@Override
public void action() {
System.out.println("RecieverB執行請求!");
}
}
class RecieverC implements Reciever { //烤魚的廚師
@Override
public void action() {
System.out.println("RecieverC執行請求!");
}
}
//用來宣告執行操作的介面
public abstract class Command {
//命令類,服務員手裡的訂單,訂單裡面包含了客戶想要什麼廚師做的菜
protected Reciever reciever;
public Command(Reciever reciever) {
this.reciever = reciever;
}
public abstract void execute();
}
// 將一個接收者物件繫結於一個動作,呼叫接收者相應的操作,以實現execute
class ConcreteCommand extends Command {
public ConcreteCommand(Reciever reciever) {
super(reciever);
}
@Override
public void execute() {
reciever.action();
}
}
//要求該命令執行這個請求
public class Invoker {//服務員,擁有很多訂單
private List<Command> list = new ArrayList();
public void addCommand(Command command) {
list.add(command);
}
public void executeCommand() {
for (Command command:list) {
command.execute();
}
}
}
//建立一個具體命令物件並設定它的接收者
public class CommandClient {
public static void main(String[] args) {
Reciever recieverA = new RecieverA();
Reciever recieverB = new RecieverB();
Reciever recieverC = new RecieverC();
Command commandA = new ConcreteCommand(recieverA);
Command commandB = new ConcreteCommand(recieverB);
Command commandC = new ConcreteCommand(recieverC);
Invoker invoker = new Invoker();
invoker.addCommand(commandA);
invoker.addCommand(commandB);
invoker.addCommand(commandC);
invoker.executeCommand();
}
}
輸出:
RecieverA執行請求!
RecieverB執行請求!
RecieverC執行請求!
//所有具體享元類的超類,接受並作用於外部狀態
public abstract class FlyWeight {
public abstract void operation(int extrinsicState);
}
class ConcreteFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicState) {
System.out.println("具體FlyWeight:" extrinsicState);
}
}
class UnsharedConcreteFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicState) {
System.out.println("不共享的具體FlyWeight:" extrinsicState);
}
}
//享元工廠
public class FlyWeightFactory {
private HashMap<String, FlyWeight> flyWeights = new HashMap<String, FlyWeight>();
public FlyWeight getFlyWeight(String key) {
if (!flyWeights.containsKey(key)) {
flyWeights.put(key, new ConcreteFlyWeight());
}
return flyWeights.get(key);
}
}
public class FlyWeightClient {
public static void main(String[] args) {
int extrinsicState = 22;
FlyWeightFactory f = new FlyWeightFactory();
FlyWeight fx = f.getFlyWeight("X");
fx.operation(--extrinsicState);
FlyWeight fy = f.getFlyWeight("Y");
fy.operation(--extrinsicState);
FlyWeight fz = f.getFlyWeight("Z");
fz.operation(--extrinsicState);
FlyWeight uf = new UnsharedConcreteFlyWeight();
uf.operation(--extrinsicState);
}
}
輸出:
具體FlyWeight:21
具體FlyWeight:20
具體FlyWeight:19
不共享的具體FlyWeight:18
//為該物件結構中ConcreteElement的每一個類宣告一個Visit操作 public abstract class Visitor { //抽象狀態 public abstract void visitConcreteElementA(ConcreteElementA concreteElementA); public abstract void visitConcreteElementB(ConcreteElementB concreteElementB); }
//定義一個accept操作,它以一個訪問者為引數 public abstract class Element { //抽象人 public abstract void accept(Visitor visitor); } class ConcreteElementA extends Element { //具體男人 @Override public void accept(Visitor visitor) { //男人接受狀態後的反應 visitor.visitConcreteElementA(this); } } class ConcreteElementB extends Element { //具體女人 @Override public void accept(Visitor visitor) { //女人接受狀態後的反應 visitor.visitConcreteElementB(this); } }
//提供一個高層的介面以允許訪問者訪問它的元素 public class ObjectStructure { //定義一個容器用來儲存男人、女人這種不變的資料結構 private List<Element> elements = new ArrayList<Element>(); public void attach(Element element) { elements.add(element); } public void detach(Element element) { elements.remove(element); } public void accept(Visitor visitor) { //遍歷所有資料結構執行他們的方法 for (Element element : elements) { element.accept(visitor); } } }
public class VisitorClient { public static void main(String[] args) { ObjectStructure o = new ObjectStructure(); o.attach(new ConcreteElementA()); o.attach(new ConcreteElementB()); ConcreteVisitor1 visitor1 = new ConcreteVisitor1(); ConcreteVisitor2 visitor2 = new ConcreteVisitor2(); o.accept(visitor1); o.accept(visitor2); } } 輸出: ConcreteElementA被ConcreteVisitor1訪問 ConcreteElementB被ConcreteVisitor1訪問 ConcreteElementA被ConcreteVisitor2訪問 ConcreteElementB被ConcreteVisitor2訪問
写评论
很抱歉,必須登入網站才能發佈留言。