作者:強子 本文摘自:
http://blog.csdn.net/liqj2ee/archive/2005/03/09/315619.aspx
////////////////////////////////////////////////////////////////////
創建模式
////////////////////////////////////////////////////////////////////
//FactoryMethod模式的例子
package pattern.a.factoryMethod;
interface Product {
?
? void operation();
}
class ConProduct1 implements Product {
?
? //不同的實現可以有不同的產品操作
? public void operation() {}
}
class ConProduct2 implements Product {
?
? //不同的實現可以有不同的產品操作
? public void operation() {}
}
interface Factory {
?
? Product CreateProduct();
? void operation1();
?
}
class ConFactory1 implements Factory {
?
? //不同的實體場類 在創建產品是可以有不能的創建方法
? public Product CreateProduct() {
????? Product product = new ConProduct1();
????? operation1();
????? return product;
? }
?
? public void operation1() {}
? public static Factory getFactory() {
????? return new ConFactory1();
? }
}
class ConFactory2 implements Factory {
?
? //不同的實體場類 在創建產品是可以有不能的創建方法
? public Product CreateProduct() {
????? Product product = new ConProduct2();
????? operation1();
????? return product;
? }
?
? public void operation1() {}
? //
? public static Factory getFactory() {
????? return new ConFactory2();
? }
}
public class FactoryMethod {
? public static void main(String[] args) {
????? Factory factory = ConFactory1.getFactory();
????? Product product = factory.CreateProduct();
????? product.operation();
? }
}
***********************************************************************
//AbstractoryFactory模式的例子
//我覺得這個模式與FactoryMethod 就是創建產品的數量上有區別
package pattern.a.abstractfactory;
//產品A的接口和實現
interface ProductA {}
class ProductA1 implements ProductA {}
class PorductA2 implements ProductA {}
//產品B的接口和實現
interface ProductB {}
class ProductB1 implements ProductB {}
class ProductB2 implements ProductB {}
//工程和工廠的實現
interface Factory {
???
??? ProductA CreateA();
???
??? ProductB CreateB();
}
//1工廠產生1系列產品
class ConFactory1 implements Factory {
???
??? public ProductA CreateA() {
??????? return new ProductA1();
??? }
???
??? public ProductB CreateB() {
??????? return new ProductB1();
??? }
???
}
//2工廠產生2系列產品
class ConFactory2 implements Factory {
???
??? public ProductA CreateA() {
??????? return new PorductA2();
??? }
???
??? public ProductB CreateB() {
??????? return new ProductB2();
??? }
???
}
class ConFactory {}
public class AbstractFactory {
??? public static void main(String[] args) {
??????? //1工廠產生1類產品
??????? Factory factory1 = new ConFactory1();
??????? ProductA a1 = factory1.CreateA();
??????? ProductB b1 = factory1.CreateB();
???????
??????? //2工廠產生2類產品
??????? Factory factory2 = new ConFactory1();
??????? ProductA a2 = factory2.CreateA();
??????? ProductB b2 = factory2.CreateB();???????
??? }
}
***********************************************************************
//Builder模式的例子
// 模式的宗旨是 將部件創建的細節 和部件的組裝方法分離!!! 考兄弟悟性要高
package pattern.a.builder;
class director {
???
??? //construct 中存放著組裝部件的邏輯 注意 邏輯的分離
??? public Product construct(Builder builder) {
??????? builder.buildPart1();
??????? builder.buildPart2();
??????? operation();
??????? Product product = builder.retrieveProduct();
??????? return product;
??? }
???
??? public void operation() {}
}
class Product {}
interface Builder {
???
??? void buildPart1();
???
??? void buildPart2();
???
??? Product retrieveProduct();
???
}
class ConBuilder1 implements Builder {
???
??? public void buildPart1() {}
???
??? public void buildPart2() {}
???
??? public Product retrieveProduct() {
??????? return null;
??? }
???
}
class ConBuilder2 implements Builder {
???
??? public void buildPart1() {}
???
??? public void buildPart2() {}
???
??? public Product retrieveProduct() {
??????? return null;
??? }???
???
}
public class BuilderPattern {
??? public static void main(String[] args) {
??? }
???
}
***********************************************************************
//Singleton模式例子
package pattern.a.singleton;
// 一種簡單的形式
class SingletonExample {
?
?private static SingletonExample instance;
?
?private SingletonExample() {}
?
?public static SingletonExample getInstance() {
??
??if (instance == null) {
???instance = new SingletonExample();
??}
??return instance;
?}??
?
?synchronized public static SingletonExample getInstance1() {
??
??if (instance == null) {
???instance = new SingletonExample();
??}
??return instance;
??
?}?
?
?public static SingletonExample getInstance2() {
??
??synchronized(SingletonExample.class) {
???if (instance == null) {
????instance = new SingletonExample();
???}
??}
??return instance;
??
?}
}
//利用類加載時 初始化只產生一次
class SingletonExample2 {
?
?private static SingletonExample2 instance = new SingletonExample2();
?
?private SingletonExample2() {}
?
?public static SingletonExample2 getInstance() {
??
??return instance;
??
?}
}
public class SingletonPattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
//Prototype模式例子
package pattern.a.prototype;
interface Prototype {
??? Prototype myclone();
}
class ConPrototype1 implements Prototype{
??? private String a;
???
??? public ConPrototype1(String a) {
??????? this.a = a;
??? }
???
??? public Prototype myclone() {
??????? return new ConPrototype1(a);
??? }
}
class ConPrototype2 implements Prototype{
??? private int b;
???
??? public ConPrototype2(int b) {
??????? this.b = b;
??? }
???
??? public Prototype myclone() {
??????? return new ConPrototype2(b);
??? }
}
public class PrototypePattern {
??? public static void main(String[] args) {
??????? Prototype inst1 = new ConPrototype1("testStr1");
??????? Prototype inst2 = null;
??????? inst2 = inst1.myclone();
??? }
}
***********************************************************************
////////////////////////////////////////////////////////////////////
結構模式
////////////////////////////////////////////////////////////////////
//Adapter模式的例子
package pattern.b.Adapter;
// 類適配
interface Target1 {
?
?void request();
?
}
class Adaptee1 {
?
??? public void specRequest() {}
}
class Adapter1 extends Adaptee1 implements Target1 {
?public void request() {
??super.specRequest();
?}
}
//對象適配
interface Target2 {
?
?void request();
}
class Adaptee2 {
??? public void specRequest() {}
}
class Adapter2 implements Target2 {
?private Adaptee2 adaptee;
?
?public Adapter2(Adaptee2 adaptee) {
??this.adaptee = adaptee;
?}
?
?public void request() {
??? ?adaptee.specRequest();
?}
}
public class AdapterPattern {
?public static void main(String[] args) {
?}
?
}
***********************************************************************
//Proxy模式例子
package pattern.b.proxy;
interface Subject {
?
?void request();
?
}
//真正處理請求的地方
class RealSubject implements Subject {
?
?public void request() {
??
??System.out.println("real access");
??
?}
?
}
//ProxySubject是與用戶交互的類 他是REalSubject的代理
//在處理功能之上的一層? 這里可以做前操作 后操作 例如可以驗證是否處理請求。
class ProxySubject implements Subject {
?
?private RealSubject real;
?
?public ProxySubject(RealSubject real) {
??this.real = real;
?}
?
?//
?public void request() {
??
??preRequest();
??real.request();
??afterRequest();
??
?}
?
?private void preRequest() {}
?
?private void afterRequest() {}
?
}
//java自身提供代理類使用反射機制
public class ProxyPattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
//Composite 模式例子
//在用戶的角度 并不知道 不見是單獨的還是符合的 只要調用接口級方法 operation
package pattern.b.composite;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// 安全模式 在接口級只提供部分功能 leaf 和 composite 有不同的功能
interface Component1 {
???
??? public void operation();
???
}
class leaf1 implements Component1 {
???
??? public void operation() {
??????? System.out.println("this is the leaf1");
??? }
???
}
class Composite1 implements Component1 {
??? private List components;
???
??? public Composite1() {
??????? components = new ArrayList();
??? }
???
??? public void operation() {
??????? Iterator it = components.iterator();
??????? Component1 com = null;
??????? while (it.hasNext()) {
??????????? com = (Component1) it.next();
??????????? com.operation();
??????? }
??? }
???
??? public void addComponent(Component1 com) {
??????? components.add(com);
??? }
???
??? public void removeComponent(int index) {
??????? components.remove(index);
??? }
???
}
// 透明模式 接口定義全部功能 leaf中可能使用空方法或拋出異常 活著寫一層 抽象類 寫上默認實現方法(極端情況下 是空或異常)
interface Component2 {
???
??? public void operation();
???
??? public void addComponent(Component2 com);
???
??? public void removeComponent(int index);
???
}
class leaf2 implements Component2 {
???
??? public void operation() {
??????? System.out.println("this is the leaf1");
??? }
???
??? //這個使用空方法
??? public void addComponent(Component2 com) {}
???
??? //這個使用不支持異常
??? public void removeComponent(int index){
??????? throw new UnsupportedOperationException();
??? }
}
class Composite2 implements Component2 {
??? private List components;
???
??? public Composite2() {
??????? components = new ArrayList();
??? }
???
??? public void operation() {
??????? Iterator it = components.iterator();
??????? Component2 com = null;
??????? while (it.hasNext()) {
??????????? com = (Component2) it.next();
??????????? com.operation();
??????? }
??? }
???
??? public void addComponent(Component2 com) {
??????? components.add(com);
??? }
???
??? public void removeComponent(int index) {
??????? components.remove(index);
??? }
???
}
//也可以用一個抽象類
abstract class AbstractComponent implements Component2{
??? public void operation() {}
???
??? public void addComponent(Component2 com) {}
???
??? abstract public void removeComponent(int index);???
}
public class CompositePattern {
??? public static void main(String[] args) {
??? }
???
}
***********************************************************************
//Flywight 模式例子
// 將共同的跟不同的屬性分離? 共享共同屬性 而不同屬性由外部傳入 進行特定操作
package pattern.b.flyweight;
import java.util.HashMap;
import java.util.Map;
// 1沒有辦法通過obj.value方式 2沒有改變屬性的方法 3不能通過繼承重置屬性 所以這個對象是 immutable 不可變的
final class State {
??? private String value = null;
???
??? public State(String value) {
??????? this.value = value;
??? }
???
??? public String getValue() {
??????? return value;
??? }
}
interface Flyweight {
??? void operation(String extrinsicState);
}
class ConFlyweight1 implements Flyweight {
??? //state 表示享元的內部狀態
??? //或者用構造函數傳入
??? private State state = new State("state1");
???
??? //out 為外部傳給享元的 外部狀態
??? public void operation(String out) {
??????? //使用外部狀態和內部狀態來執行 operation操作
??????? System.out.println("ConFlyweight1: " + out + state.getValue());
??? }
}
// 充數的
class ConFlyweight2 implements Flyweight {
??? private State state = new State("state2");
???
??? public void operation(String out) {
??????? System.out.println("ConFlyweight2: " + state.getValue() + out );
??? }
}
class FlyweightFactory {
??? Map flyweights = new HashMap();
???
??? public Flyweight getFlyweight(String key) {
??????? if (flyweights.containsKey(key)) {
??????????? return (Flyweight) flyweights.get(key);
??????? } else {
??????????? // 這里就隨便寫的
??????????? Flyweight flyweight = null;
??????????? if (key.charAt(key.length() - 1) == '1') {
??????????????? flyweight = new ConFlyweight1();
??????????????? flyweights.put(key, flyweight);
??????????? } else {
??????????????? flyweight = new ConFlyweight2();
??????????????? flyweights.put(key, flyweight);
??????????? }
??????????? return flyweight;
??????? }
??? }
}
public class FlyweightPattern {
??? public static void main(String[] args) {
??????? FlyweightFactory factory = new FlyweightFactory();
??????? Flyweight flyweight1a = factory.getFlyweight("flytest1");
??????? flyweight1a.operation("outparam1");
??? }
}
***********************************************************************
// Bridge 模式例子
//對一處的操作 改成引用一個對象 具體操作再另一個對象中進行 這樣便于功能擴展
package pattern.b.bridge;
interface Implementor {
??? void realOperation();
}
class ConImplementor1 implements Implementor {
??? public void realOperation() {
??????? System.out.println("do the real operation1");
??? }
}
class ConImplementor2 implements Implementor {
??? public void realOperation() {
??????? System.out.println("do the real operation2");
??? }
}
abstract class Abstraction {
??? protected Implementor imp;
???
??? public Abstraction(Implementor imp) {
??????? this.imp = imp;
??? }
???
??? protected void med0() {}
???
??? abstract public void operation();
}
class ConAbstraction extends Abstraction{
??? public ConAbstraction(Implementor imp) {
??????? super(imp);
??? }
???
??? public void operation() {
??????? med0();
??????? imp.realOperation();
??? }
}
public class BridgePattern {
??? public static void main(String[] args) {
??????? Implementor imp = new ConImplementor1();
??????? Abstraction abs = new ConAbstraction(imp);
??????? abs.operation();
??? }
}
***********************************************************************
//Decorator 模式例子
package pattern.b.decorator;
//源部件和修飾類的共同接口
interface Component {
??? void operation();
}
class ConComponent implements Component {
??? public void operation() {
??????? System.out.println("the begin operation");
??? }
}
//沒有提供給component賦值的方法 所以聲明這個類為抽象的 這里并沒有抽象的方法就是不像讓這個類有實例
abstract class Decotor implements Component{
??? private Component component;
???
??? public void operation() {
??????? component.operation();
??? }
}
class ConDecotor1 extends Decotor {
??? private Component component;
???
??? public ConDecotor1(Component component) {
??????? this.component = component;
??? }???
???
??? public void operation() {
??????? super.operation();
??????? //!!注意這里 這里提供了功能的添加
??????? // 這里就是Decorator的核心部分 不是修改功能而是添加功能 將一個component傳入裝飾類調用對象的接口
??????? //方法 在此過程添加功能 重新實現接口方法的功能
??????? med0();
??? }
???
??? private void med0() {
??????? System.out.println("1");
??? }
}
class ConDecotor2 extends Decotor {
??? private Component component;
???
??? public ConDecotor2(Component component) {
??????? this.component = component;
??? }???
???
??? public void operation() {
??????? super.operation();
??????? med0();
??? }
???
??? private void med0() {
??????? System.out.println("2");
??? }
}
//class?
public class DecoratorPattern {
??? public static void main(String[] args) {
??????? //注意 起點位置是從一個ConComponent開始的!!
??????? Component component = new ConDecotor2(new ConDecotor1(new ConComponent()));
??????? component.operation();
??? }
}
***********************************************************************
//Facade 的例子
//在子系統上建立了一層 對外使用感覺比較簡單 Facade的方法中封裝與子系統交互的邏輯
package pattern.b.facade;
class Exa1 {
??? public void med0() {}
}
class Exa2 {
??? public void themed() {}
}
//這就是一個簡單的Facade的方法的例子
class Facade {
??? public void facdeMed() {
??????? Exa1 exa1 = new Exa1();
??????? exa1.med0();
???????
??????? Exa2 exa2 = new Exa2();
??????? exa2.themed();
??? }
}
public class FacadePattern {
??? public static void main(String[] args) {
??? }
}
***********************************************************************
////////////////////////////////////////////////////////////////////
行為模式
////////////////////////////////////////////////////////////////////
//Command 模式例子
//感覺將一個類的方法 分散開了 抽象成了接口方法 注意 參數和返回值要一致
//每個Command封裝一個命令 也就是一種操作
package pattern.c.command;
//這個是邏輯真正實現的位置
class Receiver {
??? public void med1() {}
???
??? public void med2() {}
}
interface Command {
??? // 要抽象成統一接口方法 是有局限性的
??? void execute();
}
class ConCommand1 implements Command{
??? private Receiver receiver;
???
??? public ConCommand1(Receiver receiver) {
??????? this.receiver = receiver;
??? }
???
??? public void execute() {
??????? receiver.med1();
??? }
}
class ConCommand2 implements Command{
??? private Receiver receiver;
???
??? public ConCommand2(Receiver receiver) {
??????? this.receiver = receiver;
??? }
???
??? public void execute() {
??????? receiver.med2();
??? }
}
class Invoker {
??? private Command command;
???
??? public Invoker(Command command) {
??????? this.command = command;
??? }
???
??? public void action() {
??????? command.execute();
??? }
}
public class CommandPattern {
??? public static void main(String[] args) {
??????? Receiver receiver = new Receiver();
??????? // 生成一個命令
??????? Command command = new ConCommand1(receiver);
??????? Invoker invoker = new Invoker(command);
??????? invoker.action();
??? }
}
***********************************************************************
//Strategy 模式例子
//Strategy中封裝了算法
package pattern.c.strategy;
interface Strategy {
??? void stMed();
}
class Constrategy1 implements Strategy? {
??? public void stMed() {}
}
class constrategy2 implements Strategy? {
??? public void stMed() {}
}
class Context {
??? private Strategy strategy;
???
??? public Context (Strategy strategy) {
??????? this.strategy = strategy;
??? }
???
??? public void ContextInterface() {
??????? strategy.stMed();
??? }
}
public class StrategyPattern {
??? public static void main(String[] args) {
??? }
}
***********************************************************************
//State模式例子
//將一種狀態和狀態的助理封裝倒state中
package pattern.c.state;
class Context {
?private State state = new CloseState();
?
?public void changeState(State state) {
??this.state = state;
?}
?
?public void ruquest() {
??state.handle(this);
?}
}
interface State {
?void handle(Context context);
}
//表示打開狀態
class OpenState implements State{
?public void handle(Context context) {
??System.out.println("do something for open");
??context.changeState(new CloseState());
?}
}
//表示關閉狀態
class CloseState implements State{
?public void handle(Context context) {
??System.out.println("do something for open");
??context.changeState(new OpenState());
?}
}
public class StatePattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
//Visitor模式例子
//雙向傳入
package pattern.c.visitor;
import java.util.*;
interface Visitor {
?void visitConElementA(ConElementA conElementA);
?void visitConElementB(ConElementB conElementB);
}
class ConVisitor1 implements Visitor{
?public void visitConElementA(ConElementA conElementA) {
??String value = conElementA.value;
??conElementA.operation();
??//do something
?}
?public void visitConElementB(ConElementB conElementB) {
??String value = conElementB.value;
??conElementB.operation();
??????? //do something
?}
}
class ConVisitor2 implements Visitor{
?public void visitConElementA(ConElementA conElementA) {
??String value = conElementA.value;
??conElementA.operation();
??????? //do something
?}
?public void visitConElementB(ConElementB conElementB) {
??String value = conElementB.value;
??conElementB.operation();
??????? //do something
?}
}
interface Element {
?void accept(Visitor visitor);
}
class ConElementA implements Element {
?String value = "aa";
?
?public void operation() {}
?
?public void accept(Visitor visitor) {
??visitor.visitConElementA(this);
?}
}
class ConElementB implements Element {
?String value = "bb";
?
?public void operation() {}
?
?public void accept(Visitor visitor) {
??visitor.visitConElementB(this);
?}
}
class ObjectStructure {
?private List Elements = new ArrayList();
?
?public void action(Visitor visitor) {
??Iterator it = Elements.iterator();
??Element element = null;
??while (it.hasNext()) {
???element = (Element) it.next();
???element.accept(visitor);
??}
?}
?
?public void add(Element element) {
??Elements.add(element);
?}?
}
public class VisitorPattern {
?public static void main(String[] args) {
??ObjectStructure objs = new ObjectStructure();
??objs.add(new ConElementA());
??objs.add(new ConElementA());
??objs.add(new ConElementB());
??objs.action(new ConVisitor1());
?}
}
***********************************************************************
//Observer模式例子
package pattern.c.observable;
import java.util.*;
class State {}
interface Subject {
?void attach(Observer observer);
?
?void detach(Observer observer);
?
?void myNotify();
?
?State getState();
?
?void setState(State state);
}
class ConSubject implements Subject {
?List observers = new ArrayList();
?State state = new State();
?
?public void attach(Observer observer) {
??observers.add(observer);
?}
?
?public void detach(Observer observer) {
??observers.remove(observer);
?}
?
?public void myNotify() {
??Iterator it = observers.iterator();
??Observer observer = null;
??while (it.hasNext()) {
???observer = (Observer) it.next();
???observer.update();
??}
?}
?
?public State getState() {
??return state;
?}
?
?public void setState(State state) {
??this.state = state;
?}?
}
interface Observer {
?void update();
}
class ConObserver1 implements Observer{
?private Subject subject;
?
?public ConObserver1(Subject subject) {
??this.subject = subject;
?}
?
?public void update() {
??State state = subject.getState();
??// do something with state
?}
}
class ConObserver2 implements Observer{
?private Subject subject;
?
?public ConObserver2(Subject subject) {
??this.subject = subject;
?}
?
?public void update() {
??State state = subject.getState();
??// do something with state
?}
}
public class ObservablePattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
//Mediator模式例子
package pattern.c.mediator;
public interface Colleague {
???
??? void setState(String state);
???
??? String getState();
???
??? void change();
???
??? void action();
???
}
package pattern.c.mediator;
public class ConColleague1 implements Colleague {
???
??? private String state = null;
??? private Mediator mediator;
???
??? public void change() {
??????? mediator.changeCol1();
??? }
???
??? public ConColleague1 (Mediator mediator) {
??????? this.mediator = mediator;
??? }
???
??? public void setState(String state) {
??????? this.state = state;
??? }
???
??? public String getState() {
??????? return state;
??? }
???
??? public void action() {
??????? System.out.println("this 2 and the state is " + state);
??? }
}
package pattern.c.mediator;
public class ConColleague2 implements Colleague {
???
??? private String state = null;
??? private Mediator mediator;
???
??? public ConColleague2 (Mediator mediator) {
??????? this.mediator = mediator;
??? }???
???
??? public void change() {
??????? mediator.changeCol2();
??? }???
???
??? public void setState(String state) {
??????? this.state = state;
??? }
???
??? public String getState() {
??????? return state;
??? }
???
??? public void action() {
??????? System.out.println("this 1 and the state is " + state);
??? }???
}
package pattern.c.mediator;
public class ConMediator implements Mediator {
???
??? private ConColleague1 con1;
??? private ConColleague2 con2;
???
??? public void setCon1(ConColleague1 con1) {
??????? this.con1 = con1;
??? }
???
??? public void setCon2(ConColleague2 con2) {
??????? this.con2 = con2;
??? }
???
??? public void changeCol1() {
??????? String state = con1.getState();
??????? con2.setState(state);
??????? con2.action();
??? }
???
??? public void changeCol2() {
??????? String state = con2.getState();
??????? con1.setState(state);
??????? con1.action();???????
??? }
???
}
package pattern.c.mediator;
public interface Mediator {
???
??? void setCon1(ConColleague1 con1);
???
??? void setCon2(ConColleague2 con2);
???
??? void changeCol1();
???
??? void changeCol2();
???
}
package pattern.c.mediator;
public class MediatorTest {
???
??? public static void main(String[] args) {
??????? Mediator mediator = new ConMediator();
???????
??????? ConColleague1 col1 = new ConColleague1(mediator);
??????? col1.setState("lq test in the MediatorTest main 18");
??????? ConColleague2 col2 = new ConColleague2(mediator);
???????
??????? mediator.setCon1(col1);
??????? mediator.setCon2(col2);
???????
??????? col1.change();
??? }
???
}
***********************************************************************
//Iterator模式例子
package pattern.c.iterator;
interface Aggregate {
?MyIterator Iterator();
}
class ConAggregate {
?public MyIterator Iterator() {
??return new ConMyIterator();
?}
}
interface MyIterator {
?Object First();
?Object Last();
?boolean hasNext();
?Object Next();
}
class ConMyIterator implements MyIterator{
?Object[] objs = new Object[100];
?int index = 0;
?
?public Object First() {
??index = 0;
??return objs[index];
?}
?
?public Object Last() {
??index = objs.length - 1;
??return objs[index];
?}
?
?public boolean hasNext() {
??return index < objs.length;
?}
?
?public Object Next() {
??if (index == objs.length - 1) {
???return null;
??} else {
???return objs[++index];
??}
?}
}
public class IteratorPattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
// Template Method 模式例子
package pattern.c.template_method;
abstract class father {
?abstract void med0();
?
?abstract void med1();
?
?//operation為一個模板方法
?public void operation() {
??med0();
??med1();
??// and other logic
?}
}
class child extends father {
?public void med0() {
??System.out.println("the med0 method");
?}
?
?public void med1() {
??System.out.println("the med1 method");
?}
}
public class TemplateMethodPattern {
?public static void main(String[] args) {
?}
}
***********************************************************************
//Chain of Responsiblity模式例子
//將請求在鏈上傳遞
//如果是當前節點的請求就結束傳遞處理請求否則向下傳遞請求
//每個節點有另一個節點的引用 實現鏈狀結構
package pattern.c.chain_of_responsiblity;
interface Handler{
?void handleRequest(int key);
}
class ConHandler1 implements Handler {
?private Handler handler;
?
?public ConHandler1(Handler handler) {
??this.handler = handler;
?}
?
?public void handleRequest(int key) {
??if (key == 1) {
???System.out.println("handle in 1");
???//handle something
??} else {
???handler.handleRequest(key);
??}
?}
}
class ConHandler2 implements Handler {
?private Handler handler;
?
?public ConHandler2(Handler handler) {
??this.handler = handler;
?}
?
?public void handleRequest(int key) {
??if (key == 2) {
???System.out.println("handle in 2");
???//handle something
??} else {
???handler.handleRequest(key);
??}
?}
}
class ConHandler3 implements Handler {
?private Handler handler;
?
?public ConHandler3(Handler handler) {
??this.handler = handler;
?}
?
?public void handleRequest(int key) {
??if (key == 3) {
???System.out.println("handle in 3");
???//handle something
??} else {
???handler.handleRequest(key);
??}
?}
}
public class ChainOfResponsiblityPattern {
?public static void main(String[] args) {
??Handler handler = new ConHandler2(new ConHandler1(new ConHandler3(null)));
??handler.handleRequest(3);
?}
}
***********************************************************************
//Interpreter模式例子
/*
?* Variable 表示變量 存儲在上下文中
?* Constant 終結表達式
?* And 與的關系 雙目
?* Not 反的關系 單目
?*/
package pattern.c.interpreter;
import java.util.*;
class Context {
??? private Map variables = new HashMap();
???
??? public boolean lookUp(Variable name) {
??????? Boolean value = (Boolean) variables.get(name);
??????? if (value == null) {
??????????? return false;
??????? }
??????? return value.booleanValue();
??? }
???
??? public void bind(Variable name, boolean value) {
??????? variables.put(name, new Boolean(value));
??? }
}
interface Expression {
??? boolean interpret(Context cont);
}
class Constant implements Expression {
??? private boolean value;
???
??? public Constant(boolean value) {
??????? this.value = value;
??? }
???
??? public boolean interpret(Context cont) {
??????? return value;
??? }
}
class Variable implements Expression{
??? private String name;
???
??? public Variable(String name) {
??????? this.name = name;
??? }
???
??? public boolean interpret(Context cont) {
??????? return cont.lookUp(this);
??? }
}
class And implements Expression {
??? private Expression left;
??? private Expression right;
???
??? public And(Expression left, Expression right) {
??????? this.left = left;
??????? this.right = right;
??? }
???
??? public boolean interpret(Context cont) {
??????? return left.interpret(cont) && right.interpret(cont);
??? }
}
class Not implements Expression {
??? private Expression expression;
???
??? public Not(Expression expression) {
??????? this.expression = expression;
??? }
???
??? public boolean interpret(Context cont) {
??????? return ! expression.interpret(cont);
??? }
}
public class InterpreterPattern {
??? public static void main(String[] args) {
??????? Context cont = new Context();
??????? Variable variable = new Variable("parameter1");
??????? cont.bind(variable, true);
??????? Expression and = new And(new Not(new Constant(true)), new And(new Constant(false), new Variable("parameter1")));
??????? //? (!(true)) && ((false)&&(true))
??????? and.interpret(cont);
??? }
}
***********************************************************************
//Memento模式例子
package pattern.c.memento;
class Memento {
??? String value1;
??? int value2;
???
??? public Memento(String value1, int value2) {
??????? this.value1 = value1;
??????? this.value2 = value2;
??? }
}
class Originator {
??? private String value1;
??? private int value2;
???
??? public Originator(String value1, int value2) {
??????? this.value1 = value1;
??????? this.value2 = value2;
??? }
???
??? public void setMemento(Memento memento) {
??????? value1 = memento.value1;
??????? value2 = memento.value2;
??? }
???
??? public Memento createMemento() {
??????? Memento memento = new Memento(value1, value2);
??????? return memento;
??? }
?
??? public void setValue1(String value1) {
??????? this.value1 = value1;
??? }
?
??? public void setValue2(int value2) {
??????? this.value2 = value2;
??? }
}
class CareTaker {
??? private Memento memento;
???
??? public Memento retrieveMemento() {
??????? return memento;
??? }
???
??? public void saveMemento(Memento memento) {
??????? this.memento = memento;
??? }
}
public class MementoPattern {
??? public static void main(String[] args) {
??????? Originator originator = new Originator("test1", 1);
??????? CareTaker careTaker = new CareTaker();
???????
??????? //保存狀態
??????? careTaker.saveMemento(originator.createMemento());
???????
??????? originator.setValue1("test2");
??????? originator.setValue2(2);
???????
??????? //恢復狀態
??????? originator.setMemento(careTaker.retrieveMemento());
??? }
}