标签:
package com.main; public abstract class Operation { void getResult(){ } }<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space: normal;"> </span></span>OperationAdd类,加操作
package com.main; public class OperationAdd extends Operation{ @Override void getResult() { // TODO Auto-generated method stub System.out.print("this add operation\n"); } }OperationMul类,乘操作
package com.main; public class OperationMul extends Operation{ @Override void getResult() { // TODO Auto-generated method stub System.out.print("this mul operation\n"); } }简单工厂类OperationFactory,静态方法根据情况返回父对象。
package com.main; public class OperationFactory { public static Operation createOperation(String operString) { // TODO Auto-generated constructor stub Operation oper=null; if(operString.equals("+")){ oper=new OperationAdd(); }else if(operString.equals("*")){ oper=new OperationMul(); } return oper; } }
package com.main; abstract class Strategy { abstract void AlgorithmInterface(); }算法类StrategyA
package com.main; public class StrategyA extends Strategy{ @Override void AlgorithmInterface() { // TODO Auto-generated method stub System.out.print("this is StrategyA"); } }算法类StrategyB
package com.main; public class StrategyB extends Strategy{ @Override void AlgorithmInterface() { // TODO Auto-generated method stub System.out.print("this is StrategyB"); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Context context=new Context(new StrategyA()); context.getResult(); context=new Context(new StrategyB()); context.getResult(); } }思想:
package com.main; abstract class Component { abstract void Operation(); }ConcreteComponent类
package com.main; public class ConcreteComponent extends Component{ @Override void Operation() { // TODO Auto-generated method stub System.out.print("this is origin decorator\n"); } }Decorator类
package com.main; public class Decorator extends Component{ private Component component; public void setComponent(Component component){ this.component=component; } @Override void Operation() { // TODO Auto-generated method stub if(component!=null){ component.Operation(); } } }ConcreteDecoratorA类
package com.main; public class ConcreteDecoratorA extends Decorator{ @Override void Operation() { // TODO Auto-generated method stub super.Operation(); System.out.print("this decorator A\n"); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { ConcreteComponent original=new ConcreteComponent(); ConcreteDecoratorA contedetorA=new ConcreteDecoratorA(); ConcreteDecoratorB contedetorB=new ConcreteDecoratorB(); contedetorA.setComponent(original); contedetorB.setComponent(contedetorA); contedetorB.Operation(); } }输出:
package com.main; abstract class Subject { abstract void Request(); }RealSubject类
package com.main; public class RealSubject extends Subject { @Override void Request() { // TODO Auto-generated method stub System.out.print("this is realSubject"); } }Proxy类
package com.main; public class Proxy extends Subject { private RealSubject realSubject; @Override void Request() { // TODO Auto-generated method stub if(realSubject==null){ realSubject=new RealSubject(); } realSubject.Request(); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Proxy proxy=new Proxy(); proxy.Request(); } }输出:
package com.main; abstract interface IFactory { abstract Operation CreateOperation(); }AddFactory类
package com.main; public class AddFactory implements IFactory { @Override public Operation CreateOperation() { // TODO Auto-generated method stub Operation oper=new OperationAdd(); return oper; } }MulFactory类
package com.main; public class MulFactory implements IFactory { @Override public Operation CreateOperation() { // TODO Auto-generated method stub Operation oper=new OperationMul(); return oper; } }
//客户端代码
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { AddFactory addFactory=new AddFactory(); Operation oper=addFactory.CreateOperation(); oper.getResult(); } }输出:
以一个为原型,进行复制后,只要修改其中某个内容就可以使用,这里的复制用深复制,也就是说必须实现Cloneable接口。
工作经验类WorkExprience:
package com.main; public class WorkExprience implements Cloneable { String time; String company; @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub WorkExprience workExprience=new WorkExprience(); return workExprience; } }简历类Resume
package com.main; public class Resume implements Cloneable{ String name; WorkExprience workExprience=new WorkExprience(); public Resume() { // TODO Auto-generated constructor stub } public void setName(String name){ this.name=name; } public void setWorkExprience(String time,String company){ workExprience.time=time; workExprience.company=company; } public Resume(WorkExprience workExp) throws CloneNotSupportedException { // TODO Auto-generated constructor stub workExprience=(WorkExprience)workExp.clone(); } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Resume object=new Resume(this.workExprience); object.name=this.name; return object; } }
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { try { Resume resume1=new Resume(); resume1.name="hzh"; resume1.setWorkExprience("2013", "company1"); Resume resume2 = (Resume)resume1.clone(); resume2.setWorkExprience("2014", "company2"); System.out.print(resume1.workExprience.time); System.out.print(resume2.workExprience.time); } catch (CloneNotSupportedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } // } }输出20132014
思想如下:
(1)目标。对一个对象原型克隆,得到另外一个对象。
(2)如果是浅复制,直接实现clone接口即可。
(3)如果是深复制,则如上所述。需要利用构造函数,实现对子对象的复制。
AbstractClass类,包含抽象方法,以及模板方法。
package com.main; abstract class AbstractClass { abstract void Operation1(); abstract void Operation2(); public void TemplateMethod(){ Operation1(); Operation2(); } }ConcreteClassA类,实现特定的方法
package com.main; public class ConcreteClassA extends AbstractClass{ @Override void Operation1() { // TODO Auto-generated method stub System.out.print("this is Operation1 by A\n"); } @Override void Operation2() { // TODO Auto-generated method stub System.out.print("this is Operation2 by A\n"); } }客户端代码:最巧妙的一点就是用抽象类作为父对象,并利用子类来实例化。
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { //抽象类虽然无法实例化,但是可以作为父对象使用,利用子类来实例化。 AbstractClass absTemp=new ConcreteClassA(); absTemp.TemplateMethod(); } }输出:
this is Operation1 by A
this is Operation2 by A
为子系统中的一组接口提供一个一致的界面,也就是将子系统中的各种调用方法组合在一个方法中,供界面程序调用。
SubSystemA类,子系统A
package com.main; public class SubSystemA { void methodA(){ System.out.print("this methodA\n"); } }
package com.main; public class SubSystemB { void methodB(){ System.out.print("this methodB\n"); } }
package com.main; public class Facade { SubSystemA subA; SubSystemB subB; public Facade() { // TODO Auto-generated constructor stub subA=new SubSystemA(); subB=new SubSystemB(); } public void method(){ subA.methodA(); subB.methodB(); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Facade facade=new Facade(); facade.method(); } }
this methodA this methodB
package com.main; import java.util.ArrayList; import java.util.List; public class Product { List<String> parts=new ArrayList<String>(); public void add(String part){ parts.add(part); } public void show(){ for (String part : parts) { System.out.print(part+"\n"); } } }Builder抽象类
package com.main; abstract class Builder { abstract void BuildPartA(); abstract void BuildPartB(); abstract Product getResult(); }ConcreteBuilder1实际构造者类
package com.main; public class ConcreteBuilder1 extends Builder{ private Product product=new Product(); @Override void BuildPartA() { // TODO Auto-generated method stub product.add("builder1 and partA"); } @Override void BuildPartB() { // TODO Auto-generated method stub product.add("builder1 and partB"); } @Override Product getResult() { // TODO Auto-generated method stub return product; } }Director类
package com.main; public class Director { public void concrete(Builder builder){ builder.BuildPartA(); builder.BuildPartB(); } }
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Director director=new Director(); ConcreteBuilder1 builder1=new ConcreteBuilder1(); //将各部分添加到product中 director.concrete(builder1); Product product=builder1.getResult(); product.show(); } }
<span style="font-size:12px;font-weight: normal;">package com.main; import java.util.ArrayList; import java.util.List; abstract class Subject { private List<Observer> observers=new ArrayList<Observer>(); public void add(Observer observer){ observers.add(observer); } public void remove(Observer observer){ observers.remove(observer); } public void notifyObserver(){ for (Observer observer : observers) { observer.update(); } } } </span>ConcreteSuject主题通知者
<span style="font-size:12px;font-weight: normal;">package com.main; public class ConcreteSubject extends Subject{ public String subjectState; } </span>ConcreteObserver 具体观察者
<span style="font-size:12px;font-weight: normal;">package com.main; public class ConcreteObserver extends Observer{ private String observerName; private ConcreteSubject concreteSubject; @Override void update() { // TODO Auto-generated method stub System.out.print("i am Observer "+concreteSubject.subjectState); } public ConcreteObserver(ConcreteSubject concreteSubject, String observerName) { this.concreteSubject=concreteSubject; this.observerName=observerName; // TODO Auto-generated constructor stub } } </span>
<span style="font-size:12px;font-weight: normal;">package com.main; abstract class Observer { abstract void update(); } </span>客户端代码:
<span style="font-size:12px;font-weight: normal;">package com.main; import java.io.Console; public class Main { public static void main(String[] args) { ConcreteSubject s=new ConcreteSubject(); //这一句是精华,让observer1绑定s,让s作为其内部引用, //可以获取s状态,同时s又添加了observer1,可以通知它 s.add(new ConcreteObserver(s,"observer1")); s.subjectState="i am subject plese update"; s.notifyObserver(); } } </span>输出:
见文章:http://blog.csdn.net/liruikqn/article/details/12888511 这里转载过来
抽象工厂模式(Abstract Factory Pattern)是工厂方法模式的进一步抽象,其英文原话"Provide an interface for creating families of related or dependent objects without specifying their concrete classes",翻译,“为创建一组相关或相互依赖的对象提供一个借口,无需指定它们的具体类”。抽象工厂模式通常是用于创一族产品,并且这族产品分不同的等级;不同的具体工厂类生产不同等级的一族产品。抽象工厂模式也有四种角色:抽象工厂、具体工厂、抽象产品和具体产品,具体解释参见“Java 工厂方法模式”一文。抽象工厂模式的类图如下:
可以看到产品族包括ProductA和ProductB两种产品,每个具体工厂都能生产这两种产品,只是ConcreteFactory1生产的等级为1的族产品;ConcreteFactory2生产的是等级为2的族产品。下面以上图为模型,写一个demo,测试抽象工厂模式。
抽象工厂:AbstractFactory接口
等级为1的产品A的method1()
等级为1的产品A的method2()
等级为1的产品B的method1()
等级为1的产品B的method2()
等级为2的产品A的method1()
等级为2的产品A的method2()
等级为2的产品B的method1()
等级为2的产品B的method2()
总结:
抽象工厂模式相对于工厂方法模式来说,每个具体工厂可以生产一族产品(即多种产品);而工厂方法模式是具体工厂生产相应的具体产品,只能生产一种产品。当产品族中只有一种产品时抽象工厂模式退化成工厂方法模式。
<span style="font-size:12px;font-weight: normal;">package com.main; abstract class State { abstract void handle(Context context); } </span>Context
<span style="font-size:12px;font-weight: normal;">package com.main; public class Context { public State state; public Context(State state) { // TODO Auto-generated constructor stub this.state=state; } public void request(){ //此处传递的是引用,可以修改本身 state.handle(this); } } </span>
<span style="font-size:12px;font-weight: normal;">package com.main; public class ConcreteStateA extends State{ @Override void handle(Context context) { // TODO Auto-generated method stub System.out.print("this is state of A\n"); context.state=new ConcreteStateB(); context.request(); } } </span>ConcreteStateB 具体状态类
<span style="font-size:12px;font-weight: normal;">package com.main; public class ConcreteStateB extends State{ @Override void handle(Context context) { // TODO Auto-generated method stub System.out.print("this is state of B\n"); } } </span>客户端代码:
<span style="font-size:12px;font-weight: normal;">package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Context context=new Context(new ConcreteStateA()); context.request(); } } </span>输出:
<span style="font-size:12px;font-weight: normal;">package com.main; abstract class Target { abstract void request(); } </span>Adaptee类
<span style="font-size:12px;font-weight: normal;">package com.main; public class Adaptee { public void specificRequest(){ System.out.print("this is specific request\n"); }; } </span>Adapter
<span style="font-size:12px;font-weight: normal;">package com.main; public class Adapter extends Target{ private Adaptee adaptee=new Adaptee(); @Override void request() { // TODO Auto-generated method stub adaptee.specificRequest(); } } </span>客户端代码:
<span style="font-size:12px;font-weight: normal;">package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Target target=new Adapter() ; target.request(); } } </span>输出:
<span style="font-size:12px;font-weight: normal;">package com.main; public class Originator { public String state; public Memento concreteMemento(){ return (new Memento(state)); } public void setMemento(Memento memento){ state=memento.state; } public void show(){ System.out.print(state+"\n"); } } </span>Memento
<span style="font-size:12px;font-weight: normal;">package com.main; public class Memento { public String state; public Memento(String state) { // TODO Auto-generated constructor stub this.state=state; } } </span>
<span style="font-size:12px;font-weight: normal;">package com.main; public class CareTaker { public Memento memento; } </span>客户端代码:
<span style="font-size:12px;font-weight: normal;">package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Originator oritor=new Originator(); oritor.state="this is stateA"; oritor.show(); //保存至备忘录 CareTaker careTaker=new CareTaker(); careTaker.memento=oritor.concreteMemento(); oritor.state="this is stateB"; //利用备忘录还原 oritor.setMemento(careTaker.memento); oritor.show(); } } </span>输出:
组合模式,将对象组合成树形结构以表示’部分-整体‘的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
package com.main; abstract class Component { public String name; public Component(String name) { // TODO Auto-generated constructor stub this.name=name; } abstract void add(Component component); abstract void remove(Component component); abstract void display(); }Leaf
package com.main; public class Leaf extends Component { public Leaf(String name) { super(name); // TODO Auto-generated constructor stub } @Override void add(Component component) { // TODO Auto-generated method stub } @Override void remove(Component component) { // TODO Auto-generated method stub } @Override void display() { // TODO Auto-generated method stub System.out.print(name+"\n"); } }Composite
package com.main; import java.util.ArrayList; import java.util.List; public class Composite extends Component { private List<Component> children=new ArrayList<Component>(); public Composite(String name) { super(name); // TODO Auto-generated constructor stub } @Override void add(Component component) { // TODO Auto-generated method stub children.add(component); } @Override void remove(Component component) { // TODO Auto-generated method stub children.remove(component); } @Override void display() { // TODO Auto-generated method stub System.out.print(name+"\n"); for (Component component : children) { component.display(); } } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Composite root=new Composite("root"); root.add(new Leaf("leafA")); root.add(new Leaf("leafB")); Composite x=new Composite("x"); x.add(new Leaf("leafxA")); x.add(new Leaf("leafxB")); root.add(x); root.display(); } }输出:
root leafA leafB x leafxA leafxB透明方式与非透明方式:
package com.main; public class Singleton { <span style="white-space:pre"> </span>private Singleton(){} <span style="white-space:pre"> </span> private static Singleton instance; <span style="white-space:pre"> </span> public String data="222"; <span style="white-space:pre"> </span> private static Object object=new Object(); <span style="white-space:pre"> </span> public static Singleton getlnstance(){ <span style="white-space:pre"> </span> if(instance==null){ <span style="white-space:pre"> </span> synchronized(object){ <span style="white-space:pre"> </span> if(instance==null) <span style="white-space:pre"> </span> instance=new Singleton(); <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> return instance; <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> return instance; <span style="white-space:pre"> </span> } }客户端测试代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { new Thread(){ public void run() { Singleton s1=Singleton.getlnstance(); System.out.print(s1.data); while(true){ try { sleep(1000); System.out.print(s1.data); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; }.start(); new Thread(){ public void run() { Singleton s2=Singleton.getlnstance(); s2.data="111"; }; }.start(); } }这里用两个线程,当第二个线程中改变单例数据时,第一个线程中的单例数据也改变。
package com.main; public class Singleton { private Singleton(){ } public String data="222"; private static Singleton instance=new Singleton(); public static Singleton getlnstance(){ return instance; } }
package com.main; abstract class Implementor { public abstract void operation(); }ConcreteImplementorA
package com.main; public class ConcreteImplementorA extends Implementor{ @Override public void operation() { // TODO Auto-generated method stub System.out.print("this is implementor A\n"); } }Abstraction
package com.main; public abstract class Abstraction { public Implementor implementor; public void setImplementor(Implementor implementor){ this.implementor=implementor; } public abstract void operation(); }ConcreteAbstraction
package com.main; public class ConcreteAbstraction extends Abstraction{ @Override public void operation() { // TODO Auto-generated method stub implementor.operation(); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Abstraction ab=new ConcreteAbstraction(); ab.setImplementor(new ConcreteImplementorA()); ab.operation(); ab.setImplementor(new ConcreteImplementorB()); ab.operation(); } }输出:
<span style="font-weight: normal;">package com.main; public class Receiver { //根据不同的命令,这里应有不同的函数 public void action(){ System.out.print("command from concreteCommand"); } } </span>
<span style="font-weight: normal;">package com.main; abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { // TODO Auto-generated constructor stub this.receiver=receiver; } abstract void execute(); } </span>ConcreteCommand
<span style="font-weight: normal;">package com.main; public class ConcreteCommand extends Command { public ConcreteCommand(Receiver receiver) { super(receiver); // TODO Auto-generated constructor stub } @Override void execute() { // TODO Auto-generated method stub receiver.action(); } } </span>Invoker
<span style="font-weight: normal;">package com.main; public class Invoker { private Command command; public void setCommand(Command command){ this.command=command; } public void executeCommand(){ command.execute(); } } </span>客户端代码:
<span style="font-weight: normal;">package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Receiver receiver=new Receiver(); //命令有很多种 Command command=new ConcreteCommand(receiver); Invoker invoker=new Invoker(); //通过invoker可以设置并执行命令 invoker.setCommand(command); invoker.executeCommand(); } }</span>输出:
<span style="font-weight: normal;">package com.main; abstract class Handler { protected Handler successor; public void setSuccessor(Handler successor){ this.successor=successor; } abstract void handleRequest(int request); } </span>ConcreteHandler
package com.main; public class ConcreteHandlerA extends Handler { @Override void handleRequest(int request) { // TODO Auto-generated method stub if(request<=10){ System.out.print("handle by A\n"); }else{ successor.handleRequest(request); } } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { Handler handlerA=new ConcreteHandlerA(); Handler handlerB=new ConcreteHandlerB(); handlerA.setSuccessor(handlerB); handlerA.handleRequest(1); handlerA.handleRequest(11); } }输出:
package com.main; abstract class Mediator { abstract void send(String message,Colleague colleague); }Colleague
package com.main; abstract class Colleague { public Mediator mediator; public Colleague(Mediator mediator) { // TODO Auto-generated constructor stub this.mediator=mediator; } }ConcreteColleague
package com.main; public class ConcreteColleagueA extends Colleague { public ConcreteColleagueA(Mediator mediator) { super(mediator); // TODO Auto-generated constructor stub } public void send(String message){ //注意这里的this传过去并非为了使用,只是告诉这个消息的发送者是谁 mediator.send(message, this); } public void notice(String message){ System.out.print("A get notice: "+message+"\n"); } }ConcreteMediator
package com.main; public class ConcreteMediator extends Mediator { <span style="white-space:pre"> </span>//在这里定义对象,其引用在客户端实现 <span style="white-space:pre"> </span>public ConcreteColleagueA colleagueA; <span style="white-space:pre"> </span>public ConcreteColleagueB colleagueB; <span style="white-space:pre"> </span>@Override <span style="white-space:pre"> </span>void send(String message, Colleague colleague) { <span style="white-space:pre"> </span>// TODO Auto-generated method stub <span style="white-space:pre"> </span>if(colleague==colleagueA){ <span style="white-space:pre"> </span>colleagueB.notice(message); <span style="white-space:pre"> </span>}else{ <span style="white-space:pre"> </span>colleagueA.notice(message); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { ConcreteMediator mediator=new ConcreteMediator(); //实现双向绑定 ConcreteColleagueA colleagueA=new ConcreteColleagueA(mediator); ConcreteColleagueB colleagueB=new ConcreteColleagueB(mediator); mediator.colleagueA=colleagueA; mediator.colleagueB=colleagueB; colleagueA.send("hello i am collagueA nice to meet you"); colleagueB.send("i am collagueB nice to meet you too"); } }输出:
package com.main; abstract class FlyWeight { abstract void operation(String data); }ConcreteFlyWeight
package com.main; public class ConcreteFlyWeightA extends FlyWeight { @Override void operation(String data) { // TODO Auto-generated method stub System.out.print("this is shared A "+data+" \n"); } }UnsharedConcreteFlyWeight
package com.main; public class UnSharedConcretedFlyWeight extends FlyWeight { @Override void operation(String data) { // TODO Auto-generated method stub System.out.print("this is unshared"+data+"\n"); } }FlyWeightFactory
package com.main; import java.util.HashMap; import java.util.Hashtable; public class FlyWeightFactory { private Hashtable<String, FlyWeight> flyWeights=new Hashtable<String, FlyWeight>(); FlyWeightFactory(){ //两个不同实例,用来共享 flyWeights.put("flyWeightA", new ConcreteFlyWeightA()); flyWeights.put("flyWeightB", new ConcreteFlyWeightB()); } public FlyWeight getFlyWeight(String key){ return flyWeights.get(key); } }
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { FlyWeightFactory flyWeightFactory=new FlyWeightFactory(); //f1和f2共享一个实例 FlyWeight f1=flyWeightFactory.getFlyWeight("flyWeightA"); FlyWeight f2=flyWeightFactory.getFlyWeight("flyWeightA"); FlyWeight uf=new UnSharedConcretedFlyWeight(); //传入不同数据 f1.operation("f1"); f2.operation("f2"); uf.operation("uf"); } }输出:
this is shared A f1 this is shared A f2 this is unshareduf
package com.main; abstract class AbstractExpression { abstract void interpret(String text); }TerminalExpression
package com.main; public class TerminalExpression extends AbstractExpression { @Override void interpret(String text) { // TODO Auto-generated method stub System.out.print("terminal interpret:"+text+"\n"); } }NonTerminalExpression
package com.main; public class NonTerminalExpression extends AbstractExpression { @Override void interpret(String text) { // TODO Auto-generated method stub System.out.print("nonterminal interpret:"+text+"\n"); } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { //根据一长段文本,根据不同类型,选择不同的解释器实例来解释 //这里只简单写一下 NonTerminalExpression nonTerExp=new NonTerminalExpression(); TerminalExpression TerExp=new TerminalExpression(); nonTerExp.interpret("aaa"); TerExp.interpret("bbb"); } }输出:
package com.main; abstract class Visitor { abstract void VistConcreteElementA(ConcreElementA elementA); abstract void VistConcreteElementB(ConcreElementB elementB); }ConcreteVisitor1
package com.main; public class ConcreteVistor1 extends Visitor { @Override void VistConcreteElementA(ConcreElementA elementA) { // TODO Auto-generated method stub System.out.print("new method to elementA from visitor1\n"); } @Override void VistConcreteElementB(ConcreElementB elementB) { // TODO Auto-generated method stub System.out.print("new method to elementB from visitor1\n"); } }Element
package com.main; abstract class Element { abstract void accept(Visitor visitor); }
package com.main; public class ConcreElementA extends Element { @Override void accept(Visitor visitor) { // TODO Auto-generated method stub //此处为添加的新的方法,根据访问者不同,调用不同的方法 visitor.VistConcreteElementA(this); } public void operationA(){ //原来的方法 } }ObjectStructure
package com.main; import java.util.ArrayList; import java.util.List; 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); } } }客户端代码:
package com.main; import java.io.Console; public class Main { public static void main(String[] args) { ObjectStructure o=new ObjectStructure(); o.attach(new ConcreElementA()); o.attach(new ConcreElementB()); //相当于调用了Visitor中的两个新的方法 o.accept(new ConcreteVistor1()); } }输出:
标签:
原文地址:http://blog.csdn.net/u012599545/article/details/51164641