六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 48|回复: 0

设计模式的例子

[复制链接]

升级  2.67%

12

主题

12

主题

12

主题

秀才

Rank: 2

积分
54
 楼主| 发表于 2013-1-27 05:02:38 | 显示全部楼层 |阅读模式
////////////////////////////////////////////////////////////////////创建模式//////////////////////////////////////////////////////////////////////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());    }} 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表