一、图示
二、代码示例
1.单例设计(Singleton)模式
public class Singleton {@b@@b@ private static Singleton instance = new Singleton(); // 在内部产生本类的实例化对象@b@@b@ public static Singleton getInstance() { // 通过静态方法取得instance对象@b@ return instance;@b@ }@b@@b@ private Singleton() { // 将构造方法进行了封装,私有化@b@ }@b@@b@ public void print() {@b@ System.out.println("Hello World!!!");@b@ }@b@@b@ public static void main(String args[]) {@b@ Singleton s1 = null; // 声明对象@b@ Singleton s2 = null; // 声明对象@b@ Singleton s3 = null; // 声明对象@b@ s1 = Singleton.getInstance(); // 取得实例化对象@b@ s2 = Singleton.getInstance(); // 取得实例化对象@b@ s3 = Singleton.getInstance(); // 取得实例化对象@b@ s1.print(); // 调用方法@b@ s2.print(); // 调用方法@b@ s3.print(); // 调用方法@b@ }@b@@b@}
2.抽象工厂(Abstract Factory)模式
//抽象工厂角色@b@public interface AbstractFactory{@b@ public ProductA createProductA(); @b@}@b@@b@//抽象产品类A@b@public interface AbstractProductA {@b@}@b@ @b@@b@//具体产品类ProdcutA1@b@public class ProductA1 implements AbstractProductA {@b@ public ProductA1() {@b@ }@b@}@b@@b@//具体产品类ProdcutA2@b@public class ProductA2 implements AbstractProductA@b@{@b@ public ProductA2() {@b@ }@b@}@b@ @b@@b@//具体工厂类1@b@public class ConcreteFactory1 implements AbstractFactory{@b@ public AbstractProductA createProductA(){@b@ return new ProductA1();@b@ }@b@ @b@}@b@@b@//具体工厂类2@b@public class ConcreteFactory2 implements Creator{@b@ public AbstractProductA createProductA(){@b@ return new ProductA2();@b@ }@b@ @b@}
3.代理(Proxy)模式
interface Network{ @b@ public void browse() ; // 浏览}class Real implements Network{ public void browse(){@b@ System.out.println("上网浏览信息") ;@b@ }@b@}@b@class Proxy implements Network{ @b@ private Network network ; // 代理对象@b@ public Proxy(Network network){ @b@ this.network = network ;@b@ } @b@ public void check(){@b@ System.out.println("检查用户是否合法。") ;@b@ } @b@ public void browse(){ @b@ this.check() ; @b@ this.network.browse() ; // 调用真实的主题操作 @b@ }@b@}@b@public class ProxyDemo{ @b@ public static void main(String args[]){@b@ Network net = null ;@b@ net = new Proxy(new Real()) ;// 指定代理操作@b@ net.browse() ; // 客户只关心上网浏览一个操作 @b@ }@b@}
4.工厂方法(Factory Method)模式
interface Fruit{ // 定义一个水果接口@b@ public void eat() ; // 吃水果}class Apple implements Fruit{ public void eat(){@b@ System.out.println("** 吃苹果。") ;@b@ }@b@}@b@class Orange implements Fruit{ public void eat(){@b@ System.out.println("** 吃橘子。") ;@b@ }@b@}@b@class Factory{ // 定义工厂类@b@ public static Fruit getInstance(String className){@b@ Fruit f = null ; if("apple".equals(className)){ // 判断是否要的是苹果的子类@b@ f = new Apple() ;@b@ } if("orange".equals(className)){ // 判断是否要的是橘子的子类@b@ f = new Orange() ;@b@ } return f ;@b@ }@b@}@b@public class InterfaceCaseDemo05{ public static void main(String args[]){@b@ Fruit f = Factory.getInstance(args[0]) ; // 实例化接口@b@ if(f!=null){ // 判断是否取得实例 f.eat() ;@b@ }@b@ }@b@};
5.适配器(Adapter)模式
interface Window { // 定义Window接口,表示窗口操作@b@ public void open(); // 打开@b@ public void close(); // 关闭@b@ public void activated(); // 窗口活动@b@ public void iconified(); // 窗口最小化@b@ public void deiconified();// 窗口恢复大小@b@}@b@abstract class WindowAdapter implements Window {@b@ public void open() {@b@ }; // 打开@b@ public void close() {@b@ }; // 关闭@b@ public void activated() {@b@ }; // 窗口活动@b@ public void iconified() {@b@ }; // 窗口最小化@b@ public void deiconified() {@b@ };// 窗口恢复大小@b@};@b@class WindowImpl extends WindowAdapter {@b@ public void open() {@b@ System.out.println("窗口打开。");@b@ }@b@ public void close() {@b@ System.out.println("窗口关闭。");@b@ }@b@};@b@public class AdapterDemo {@b@ public static void main(String args[]) {@b@ Window win = new WindowImpl();@b@ win.open();@b@ win.close();@b@ }@b@};
6.桥接(Bridge)模式
interface Implementor {@b@ // 实现抽象部分需要的某些具体功能@b@ public void operationImpl();@b@}@b@@b@abstract class Abstraction {@b@ // 持有一个 Implementor 对象,形成聚合关系@b@ protected Implementor implementor;@b@ @b@ public Abstraction(Implementor implementor) {@b@ this.implementor = implementor;@b@ }@b@ @b@ // 可能需要转调实现部分的具体实现@b@ public void operation() {@b@ implementor.operationImpl();@b@ }@b@}@b@@b@class ConcreteImplementorA implements Implementor {@b@ @Override@b@ public void operationImpl() {@b@ // 真正的实现@b@ System.out.println("具体实现A");@b@ } @b@}@b@@b@class ConcreteImplementorB implements Implementor {@b@ @Override@b@ public void operationImpl() {@b@ // 真正的实现@b@ System.out.println("具体实现B");@b@ } @b@}@b@@b@class RefinedAbstraction extends Abstraction {@b@@b@ public RefinedAbstraction(Implementor implementor) {@b@ super(implementor);@b@ }@b@ @b@ public void otherOperation() {@b@ // 实现一定的功能,可能会使用具体实现部分的实现方法,@b@ // 但是本方法更大的可能是使用 Abstraction 中定义的方法,@b@ // 通过组合使用 Abstraction 中定义的方法来完成更多的功能。@b@ }@b@}@b@@b@public class BridgePattern {@b@ public static void main(String[] args) {@b@ Implementor implementor = new ConcreteImplementorA();@b@ RefinedAbstraction abstraction = new RefinedAbstraction(implementor);@b@ abstraction.operation();@b@ abstraction.otherOperation();@b@ }@b@}
7.建造者(Builder)模式
public interface Builder { @b@ void buildPartA(); @b@ void buildPartB(); @b@ void buildPartC(); @b@ @b@ Product getResult(); @b@ } @b@@b@ @b@//具体建造工具@b@public class ConcreteBuilder implements Builder { @b@ Part partA, partB, partC; @b@@b@ public void buildPartA() {@b@ //这里是具体如何构建partA的代码@b@ }; @b@ public void buildPartB() { @b@ //这里是具体如何构建partB的代码@b@ }; @b@ public void buildPartC() { @b@ //这里是具体如何构建partB的代码@b@ }; @b@ public Product getResult() { @b@ //返回最后组装成品结果@b@ }; @b@ }@b@@b@//建造者@b@public class Director {@b@ private Builder builder; @b@ @b@ public Director( Builder builder ) { @b@ this.builder = builder; @b@ } @b@ public void construct() { @b@ builder.buildPartA();@b@ builder.buildPartB();@b@ builder.buildPartC(); @b@ } @b@ } @b@@b@@b@public interface Product { }@b@public interface Part { }@b@@b@@b@下面是调用builder的方法:@b@ConcreteBuilder builder = new ConcreteBuilder();@b@Director director = new Director( builder ); @b@@b@director.construct(); @b@Product product = builder.getResult();
8.责任链(Chain Of Responsibility)模式
public abstract class Handler { @b@ /** @b@ * 持有下一个处理请求的对象 @b@ */ @b@ protected Handler successor = null; @b@ /** @b@ * 取值方法 @b@ */ @b@ public Handler getSuccessor() { @b@ return successor; @b@ } @b@ /** @b@ * 设置下一个处理请求的对象 @b@ */ @b@ public void setSuccessor(Handler successor) { @b@ this.successor = successor; @b@ } @b@ /** @b@ * 处理聚餐费用的申请 @b@ * @param user 申请人 @b@ * @param fee 申请的钱数 @b@ * @return 成功或失败的具体通知 @b@ */ @b@ public abstract String handleFeeRequest(String user , double fee); @b@} @b@@b@public class ProjectManager extends Handler { @b@ @b@ @Override @b@ public String handleFeeRequest(String user, double fee) { @b@ @b@ String str = ""; @b@ //项目经理权限比较小,只能在500以内 @b@ if(fee < 500) @b@ { @b@ //为了测试,简单点,只同意张三的请求 @b@ if("张三".equals(user)) @b@ { @b@ str = "成功:项目经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ }else @b@ { @b@ //其他人一律不同意 @b@ str = "失败:项目经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ } @b@ }else @b@ { @b@ //超过500,继续传递给级别更高的人处理 @b@ if(getSuccessor() != null) @b@ { @b@ return getSuccessor().handleFeeRequest(user, fee); @b@ } @b@ } @b@ return str; @b@ } @b@ @b@} @b@@b@public class DeptManager extends Handler { @b@ @b@ @Override @b@ public String handleFeeRequest(String user, double fee) { @b@ @b@ String str = ""; @b@ //部门经理的权限只能在1000以内 @b@ if(fee < 1000) @b@ { @b@ //为了测试,简单点,只同意张三的请求 @b@ if("张三".equals(user)) @b@ { @b@ str = "成功:部门经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ }else @b@ { @b@ //其他人一律不同意 @b@ str = "失败:部门经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ } @b@ }else @b@ { @b@ //超过1000,继续传递给级别更高的人处理 @b@ if(getSuccessor() != null) @b@ { @b@ return getSuccessor().handleFeeRequest(user, fee); @b@ } @b@ } @b@ return str; @b@ } @b@ @b@} @b@@b@public class GeneralManager extends Handler { @b@ @b@ @Override @b@ public String handleFeeRequest(String user, double fee) { @b@ @b@ String str = ""; @b@ //总经理的权限很大,只要请求到了这里,他都可以处理 @b@ if(fee >= 1000) @b@ { @b@ //为了测试,简单点,只同意张三的请求 @b@ if("张三".equals(user)) @b@ { @b@ str = "成功:总经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ }else @b@ { @b@ //其他人一律不同意 @b@ str = "失败:总经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; @b@ } @b@ }else @b@ { @b@ //如果还有后继的处理对象,继续传递 @b@ if(getSuccessor() != null) @b@ { @b@ return getSuccessor().handleFeeRequest(user, fee); @b@ } @b@ } @b@ return str; @b@ } @b@ @b@} @b@@b@public class Client { @b@ @b@ public static void main(String[] args) { @b@ //先要组装责任链 @b@ Handler h1 = new GeneralManager(); @b@ Handler h2 = new DeptManager(); @b@ Handler h3 = new ProjectManager(); @b@ h3.setSuccessor(h2); @b@ h2.setSuccessor(h1); @b@ @b@ //开始测试 @b@ String test1 = h3.handleFeeRequest("张三", 300); @b@ System.out.println("test1 = " + test1); @b@ String test2 = h3.handleFeeRequest("李四", 300); @b@ System.out.println("test2 = " + test2); @b@ System.out.println("---------------------------------------"); @b@ @b@ String test3 = h3.handleFeeRequest("张三", 700); @b@ System.out.println("test3 = " + test3); @b@ String test4 = h3.handleFeeRequest("李四", 700); @b@ System.out.println("test4 = " + test4); @b@ System.out.println("---------------------------------------"); @b@ @b@ String test5 = h3.handleFeeRequest("张三", 1500); @b@ System.out.println("test5 = " + test5); @b@ String test6 = h3.handleFeeRequest("李四", 1500); @b@ System.out.println("test6 = " + test6); @b@ } @b@ @b@}
9.命令(Command)模式
public class Receiver {@b@ /**@b@ * 真正执行命令相应的操作@b@ */@b@ public void action(){@b@ System.out.println("执行操作");@b@ }@b@}@b@@b@public interface Command {@b@ /**@b@ * 执行方法@b@ */@b@ void execute();@b@}@b@@b@@b@public class ConcreteCommand implements Command {@b@ //持有相应的接收者对象@b@ private Receiver receiver = null;@b@ /**@b@ * 构造方法@b@ */@b@ public ConcreteCommand(Receiver receiver){@b@ this.receiver = receiver;@b@ }@b@ @Override@b@ public void execute() {@b@ //通常会转调接收者对象的相应方法,让接收者来真正执行功能@b@ receiver.action();@b@ }@b@@b@}@b@@b@public class Invoker {@b@ /**@b@ * 持有命令对象@b@ */@b@ private Command command = null;@b@ /**@b@ * 构造方法@b@ */@b@ public Invoker(Command command){@b@ this.command = command;@b@ }@b@ /**@b@ * 行动方法@b@ */@b@ public void action(){@b@ @b@ command.execute();@b@ }@b@}@b@@b@public class Client {@b@@b@ public static void main(String[] args) {@b@ //创建接收者@b@ Receiver receiver = new Receiver();@b@ //创建命令对象,设定它的接收者@b@ Command command = new ConcreteCommand(receiver);@b@ //创建请求者,把命令对象设置进去@b@ Invoker invoker = new Invoker(command);@b@ //执行方法@b@ invoker.action();@b@ }@b@@b@}
10.组合模式(Composite)
abstract class Component {@b@ protected String name;@b@ public Component(String name) {@b@ this.name = name;@b@ }@b@ public abstract void Add(Component c);@b@ public abstract void Remove(Component c);@b@ public abstract void Display(int depth);@b@@b@}@b@@b@class Leaf extends Component {@b@@b@ public Leaf(String name) {@b@ super(name);@b@ }@b@@b@ @Override@b@ public void Add(Component c) {@b@ System.out.println("Can not add to a leaf");@b@ }@b@@b@ @Override@b@ public void Remove(Component c) {@b@ System.out.println("Can not remove from a leaf");@b@@b@ }@b@@b@ @Override@b@ public void Display(int depth) {@b@ String temp = "";@b@ for (int i = 0; i < depth; i++) @b@ temp += '-';@b@ System.out.println(temp + name);@b@ }@b@@b@}@b@@b@class Composite extends Component {@b@@b@ private List<Component> children = new ArrayList<Component>();@b@@b@ public Composite(String name) {@b@ super(name);@b@ }@b@@b@ @Override@b@ public void Add(Component c) {@b@ children.add(c);@b@ }@b@@b@ @Override@b@ public void Remove(Component c) {@b@ children.remove(c);@b@@b@ }@b@@b@ @Override@b@ public void Display(int depth) {@b@ String temp = "";@b@ for (int i = 0; i < depth; i++) @b@ temp += '-';@b@ System.out.println(temp + name);@b@@b@ for (Component c : children) {@b@ c.Display(depth + 2);@b@ }@b@@b@ }@b@@b@}@b@@b@public class CompositePattern {@b@@b@ public static void main(String[] args) {@b@@b@ Composite root = new Composite("root");@b@ root.Add(new Leaf("Leaf A"));@b@ root.Add(new Leaf("Leaf B"));@b@@b@ Composite compX = new Composite("Composite X");@b@ compX.Add(new Leaf("Leaf XA"));@b@ compX.Add(new Leaf("Leaf XB"));@b@ root.Add(compX);@b@@b@ Composite compXY = new Composite("Composite XY");@b@ compXY.Add(new Leaf("Leaf XYA"));@b@ compXY.Add(new Leaf("Leaf XYB"));@b@ compX.Add(compXY);@b@@b@ root.Display(1);@b@@b@ }@b@@b@}
11.装饰者(Decorator)模式
public interface Person {@b@ void eat();@b@}@b@@b@public class Man implements Person {@b@ public void eat() {@b@ System.out.println("男人在吃");@b@ }@b@}@b@@b@public abstract class Decorator implements Person {@b@@b@ protected Person person;@b@ @b@ public void setPerson(Person person) {@b@ this.person = person;@b@ }@b@ @b@ public void eat() {@b@ person.eat();@b@ }@b@}@b@@b@public class ManDecoratorA extends Decorator {@b@@b@ public void eat() {@b@ super.eat();@b@ reEat();@b@ System.out.println("ManDecoratorA类");@b@ }@b@@b@ public void reEat() {@b@ System.out.println("再吃一顿饭");@b@ }@b@}@b@public class ManDecoratorB extends Decorator {@b@ @b@ public void eat() {@b@ super.eat();@b@ System.out.println("===============");@b@ System.out.println("ManDecoratorB类");@b@ }@b@}@b@@b@public class Test {@b@@b@ public static void main(String[] args) {@b@ Man man = new Man();@b@ ManDecoratorA md1 = new ManDecoratorA();@b@ ManDecoratorB md2 = new ManDecoratorB();@b@ @b@ md1.setPerson(man);@b@ md2.setPerson(md1);@b@ md2.eat();@b@ }@b@}
12.门面(Facade)模式
public class ModuleA {@b@ /**@b@ * 提供给子系统外部使用的方法@b@ */@b@ public void a1() {@b@ }@b@ private void a2() {@b@ }@b@ private void a3() {@b@ }@b@}@b@@b@public class ModuleB {@b@ /**@b@ * 提供给子系统外部使用的方法@b@ */@b@ public void b1() {@b@ }@b@ private void b2() {@b@ }@b@ private void b3() {@b@ }@b@}@b@@b@public class ModuleC {@b@ /**@b@ * 提供给子系统外部使用的方法@b@ */@b@ public void c1() {@b@ }@b@ private void c2() {@b@ }@b@ private void c3() {@b@ }@b@}@b@@b@public class ModuleFacade {@b@@b@ ModuleA a = new ModuleA();@b@ ModuleB b = new ModuleB();@b@ ModuleC c = new ModuleC();@b@@b@ /**@b@ * 下面这些是A、B、C模块对子系统外部提供的方法@b@ */@b@ public void a1() {@b@ a.a1();@b@ }@b@@b@ public void b1() {@b@ b.b1();@b@ }@b@@b@ public void c1() {@b@ c.c1();@b@ }@b@}
13.享元(Flyweight)模式
//抽象享元角色类@b@public interface Flyweight {@b@ //一个示意性方法,参数state是外蕴状态@b@ public void operation(String state);@b@}@b@@b@//具体享元角色类@b@public class ConcreteFlyweight implements Flyweight {@b@ private String intrinsicState = null;//内蕴状态@b@ /**@b@ * 构造函数,内蕴状态作为参数传入@b@ * @b@ * @param intrinsicState@b@ */@b@ public ConcreteFlyweight(String intrinsicState) {@b@ this.intrinsicState = intrinsicState;@b@ }@b@@b@ /**@b@ * 外蕴状态作为参数传入方法中,改变方法的行为, 但是并不改变对象的内蕴状态。@b@ */@b@ @Override@b@ public void operation(String state) {@b@ System.out.println("内蕴状态= " + this.intrinsicState);@b@ System.out.println("外蕴状态 = " + state);@b@ }@b@@b@}@b@@b@//享元工厂角色类@b@public class FlyweightFactory {@b@ // 一个用来存所有享元对象的集合 String表示对象的键的类型 ->内蕴状态 ;Flyweight表示对象值的类型@b@ private Map<String, Flyweight> files = new HashMap<String, Flyweight>();@b@@b@ public Flyweight factory(String intrinsicState) {@b@ // 先从缓存中查找对象@b@ Flyweight fly = files.get(intrinsicState);@b@ if (fly == null) {@b@ // 如果对象不存在则创建一个新的Flyweight对象@b@ fly = new ConcreteFlyweight(intrinsicState);@b@ // 把这个新的Flyweight对象添加到缓存中@b@ files.put(intrinsicState, fly);@b@ }@b@ return fly;@b@ }@b@ //得到存对象的集合的长度@b@ public int getFlyWeightSize() {@b@ return files.size();@b@ }@b@@b@}@b@@b@public class Client {@b@@b@ public static void main(String[] args) {@b@ FlyweightFactory factory = new FlyweightFactory();@b@ Flyweight fly1 = factory.factory(new String("辣椒炒肉"));@b@ fly1.operation("汤高点菜");@b@@b@ Flyweight fly2 = factory.factory(new String("牛肉"));@b@ fly2.operation("周思远点菜");@b@@b@ Flyweight fly3 = factory.factory(new String("辣椒炒肉"));@b@ fly3.operation("汤高点菜");@b@@b@ System.out.println(fly1==fly3);@b@ System.out.println("被点不同的菜的个数"+factory.getFlyWeightSize());@b@ }@b@@b@}
14.解释器(Interper)模式
class Context { @b@ private Map valueMap = new HashMap(); @b@ public void addValue(Variable x , int y) @b@ { @b@ Integer yi = new Integer(y); @b@ valueMap.put(x , yi); @b@ } @b@ @b@ public int LookupValue(Variable x) { @b@ int i = ((Integer)valueMap.get(x)).intValue(); @b@ return i ; @b@ } @b@} @b@@b@@b@abstract class Expression { @b@ public abstract int interpret(Context con); @b@ @b@} @b@@b@class Constant extends Expression { @b@ @b@ private int i ; @b@ public Constant(int i) { @b@ this.i = i; @b@ } @b@ @b@ public int interpret(Context con) { @b@ return i ; @b@ } @b@} @b@@b@class Variable extends Expression { @b@ @b@ public int interpret(Context con) { @b@ //this为调用interpret方法的Variable对象 @b@ return con.LookupValue(this); @b@ } @b@} @b@@b@class Add extends Expression { @b@ @b@ private Expression left ,right ; @b@ public Add(Expression left , Expression right) { @b@ this.left = left ; @b@ this.right= right ; @b@ } @b@ @b@ public int interpret(Context con) { @b@ return left.interpret(con) + right.interpret(con); @b@ } @b@} @b@@b@class Subtract extends Expression { @b@ @b@ private Expression left , right ; @b@ public Subtract(Expression left , Expression right) { @b@ this.left = left ; @b@ this.right= right ; @b@ } @b@ @b@ public int interpret(Context con) { @b@ return left.interpret(con) - right.interpret(con); @b@ } @b@}@b@@b@class Multiply extends Expression { @b@ @b@ private Expression left , right ; @b@ @b@ public Multiply(Expression left , Expression right) { @b@ this.left = left ; @b@ this.right= right ; @b@ } @b@ @b@ public int interpret(Context con) { @b@ return left.interpret(con) * right.interpret(con); @b@ } @b@ @b@} @b@@b@@b@class Division extends Expression { @b@ @b@ private Expression left , right ; @b@ public Division(Expression left , Expression right) { @b@ this.left = left ; @b@ this.right= right ; @b@ } @b@ @b@ public int interpret(Context con) { @b@ try{ @b@ @b@ return left.interpret(con) / right.interpret(con); @b@ }catch(ArithmeticException ae) { @b@ System.out.println("被除数为0!"); @b@ return -11111; @b@ } @b@ } @b@} @b@@b@@b@class Division extends Expression { @b@ @b@ private Expression left , right ; @b@ @b@ public Division(Expression left , Expression right) { @b@ this.left = left ; @b@ this.right= right ; @b@ } @b@ @b@ public int interpret(Context con) { @b@ try{ @b@ return left.interpret(con) / right.interpret(con); @b@ }catch(ArithmeticException ae) { @b@ System.out.println("被除数为0!"); @b@ return -11111; @b@ } @b@ } @b@ @b@}
15.迭代器(Iterator)模式
public static void main(String[] args) {@b@ List<Object> list = new ArrayList<Object>();@b@ list.add("a");@b@ list.add("b");@b@ list.add("c");@b@ Aggregate aggregate = new ConcreteAggregate(list);@b@ Iterator iterator = aggregate.iterator();@b@@b@ while (iterator.hasNext()) {@b@ String o = (String) iterator.next();@b@ System.out.println(o);@b@ }@b@ }@b@}@b@@b@interface Iterator {@b@ public Object next();@b@ public boolean hasNext();@b@@b@}@b@@b@class ConcreteIterator implements Iterator {@b@ private List<Object> list;@b@ private int cursor = 0;// 当前游标位置@b@@b@ public ConcreteIterator(List<Object> list) {@b@ this.list = list;@b@@b@ }@b@@b@ public boolean hasNext() {@b@ // TODO Auto-generated method stub@b@ return !(cursor == list.size());@b@ }@b@@b@ public Object next() {@b@ // TODO Auto-generated method stub@b@ Object obj = null;@b@ if (hasNext()) {@b@ obj = list.get(cursor++);@b@ }@b@ return obj;@b@ }@b@}@b@@b@// 模拟集合接口 增删 差(遍历)@b@interface Aggregate {@b@@b@ public void add(Object obj);@b@ public void remove(Object obj);@b@ public Iterator iterator();@b@@b@}@b@@b@class ConcreteAggregate implements Aggregate {@b@ private List<Object> list;@b@@b@ public ConcreteAggregate(List<Object> list) {@b@ this.list = list;@b@@b@ }@b@@b@ public void add(Object obj) {@b@ list.add(obj);@b@@b@ }@b@@b@ public Iterator iterator() {@b@ // TODO Auto-generated method stub@b@ return new ConcreteIterator(list);@b@ }@b@@b@ public void remove(Object obj) {@b@ list.remove(obj);@b@@b@ }@b@@b@}
16.中介者(Mediator)模式
public abstract class Mediator { @b@ public abstract void notice(String content); @b@} @b@@b@public class ConcreteMediator extends Mediator { @b@ @b@ private ColleagueA ca; @b@ private ColleagueB cb; @b@ @b@ public ConcreteMediator() { @b@ ca = new ColleagueA(); @b@ cb = new ColleagueB(); @b@ } @b@ @b@ public void notice(String content) { @b@ if (content.equals("boss")) { @b@ //老板来了, 通知员工A @b@ ca.action(); @b@ } @b@ if (content.equals("client")) { @b@ //客户来了, 通知前台B @b@ cb.action(); @b@ } @b@ } @b@} @b@@b@public class ColleagueA extends Colleague { @b@ public void action() { @b@ System.out.println("普通员工努力工作"); @b@ } @b@}@b@@b@public class ColleagueB extends Colleague { @b@ public void action() { @b@ System.out.println("前台注意了!"); @b@ } @b@} @b@@b@public class Test { @b@ public static void main(String[] args) { @b@ Mediator med = new ConcreteMediator(); @b@ //老板来了 @b@ med.notice("boss"); @b@ @b@ //客户来了 @b@ med.notice("client"); @b@ } @b@}
17.备忘录(Memento)模式
public class GameRole {@b@ private int vit;@b@ private int atk;@b@@b@ public void init(){@b@ vit=100;@b@ atk=100;@b@ }@b@ @b@ public void show(){@b@ System.out.println("体力:"+vit);@b@ System.out.println("攻击力:"+atk);@b@ }@b@ @b@ public void fightBoss(){@b@ this.vit=0;@b@ this.atk=0;@b@ }@b@ @b@ public RoleStateMemento saveMemento(){@b@ return (new RoleStateMemento(vit, atk));@b@ }@b@ @b@ public void recove(RoleStateMemento roleStateMemento){@b@ this.vit=roleStateMemento.getVit();@b@ this.atk=roleStateMemento.getAtk();@b@ }@b@}@b@@b@public class RoleStateMange {@b@ @b@ private RoleStateMemento memento;@b@ public RoleStateMemento getMemento() {@b@ return memento;@b@ }@b@ public void setMemento(RoleStateMemento memento) {@b@ this.memento = memento;@b@ }@b@ @b@}@b@@b@public class RoleStateMemento {@b@ @b@ private int vit;@b@ private int atk;@b@ @b@ public RoleStateMemento(int vit, int atk){@b@ this.vit=vit;@b@ this.atk=atk;@b@ }@b@@b@ public int getVit() {@b@ return vit;@b@ }@b@@b@ public void setVit(int vit) {@b@ this.vit = vit;@b@ }@b@@b@ public int getAtk() {@b@ return atk;@b@ }@b@@b@ public void setAtk(int atk) {@b@ this.atk = atk;@b@ }@b@}@b@@b@public class Client {@b@ public static void main(String[] args) {@b@ GameRole liaowp=new GameRole();@b@ liaowp.init();@b@ liaowp.show();@b@ RoleStateMange adminMange=new RoleStateMange();@b@ adminMange.setMemento(liaowp.saveMemento());//保存@b@ liaowp.fightBoss();@b@ liaowp.show();@b@ liaowp.recove(adminMange.getMemento());@b@ liaowp.show();@b@ @b@ }@b@}
18.观察者(Observer)模式
public interface Observer@b@{@b@ public void update(float temprature);@b@}@b@@b@public class ConcreteObserver implements Observer@b@{@b@ private float temperature;@b@ private final Subject subject;@b@@b@ public ConcreteObserver(final Subject subject)@b@ {@b@ this.subject = subject;@b@ this.subject.registerObserver(this);@b@ }@b@@b@ public float getTemperature()@b@ {@b@ return temperature;@b@ }@b@@b@ public void setTemperature(final float temperature)@b@ {@b@ this.temperature = temperature;@b@ }@b@@b@ @Override@b@ public void update(final float temperature)@b@ {@b@ this.temperature = temperature;@b@ }@b@}@b@@b@public interface Subject@b@{@b@ public void registerObserver(Observer o);@b@@b@ public void removeObserver(Observer o);@b@@b@ public void notifyObservers();@b@@b@}@b@@b@public class ConcreteSubject implements Subject@b@{@b@ private final List<Observer> observers;@b@ private float temperature;@b@@b@ public float getTemperature()@b@ {@b@ return temperature;@b@ }@b@@b@ private void temperatureChanged()@b@ {@b@ this.notifyObservers();@b@ }@b@@b@ public void setTemperature(final float temperature)@b@ {@b@ this.temperature = temperature;@b@ this.temperatureChanged();@b@ }@b@@b@ public ConcreteSubject()@b@ {@b@ observers = new ArrayList<Observer>();@b@ }@b@@b@ @Override@b@ public void registerObserver(final Observer o)@b@ {@b@ observers.add(o);@b@ }@b@@b@ @Override@b@ public void removeObserver(final Observer o)@b@ {@b@ if (observers.indexOf(o) >= 0)@b@ {@b@ observers.remove(o);@b@ }@b@ }@b@@b@ @Override@b@ public void notifyObservers()@b@ {@b@ for (final Observer o : observers)@b@ {@b@ o.update(temperature);@b@ }@b@ }@b@}@b@@b@public class Client@b@{@b@ public static void main(final String[] args)@b@ {@b@ final ConcreteSubject sb = new ConcreteSubject();@b@ sb.setTemperature((float) 20.00);@b@@b@ final Observer o = new ConcreteObserver(sb);@b@ sb.setTemperature((float) 21.00);@b@@b@ }@b@}
19.原型(Prototype)模式
//实例一:浅拷贝@b@public class Prototype implements Cloneable {@b@ private String name;@b@@b@ public String getName() {@b@ return name;@b@ }@b@@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@@b@ public Object clone() {@b@ try {@b@ return super.clone();@b@ } catch (CloneNotSupportedException e) { @b@ e.printStackTrace();@b@ return null;@b@ }@b@ } @b@ @b@}@b@@b@public class TestMain {@b@@b@ public static void main(String[] args) {@b@ testPrototype();@b@ }@b@ @b@ private static void testPrototype(){@b@ Prototype pro = new Prototype();@b@ pro.setName("original object");@b@ Prototype pro1 = (Prototype)pro.clone();@b@ pro.setName("changed object1");@b@ @b@ System.out.println("original object:" + pro.getName());@b@ System.out.println("cloned object:" + pro1.getName());@b@ @b@ }@b@@b@}@b@//结果:@b@original object:changed object1@b@cloned object:original object@b@@b@@b@//实例二: 浅拷贝@b@public class Prototype{@b@ private String name;@b@@b@ public String getName() {@b@ return name;@b@ }@b@@b@ public void setName(String name) {@b@ this.name = name;@b@ } @b@ @b@}@b@public class NewPrototype implements Cloneable {@b@ @b@ private String id;@b@ @b@ public String getId() {@b@ return id;@b@ }@b@@b@ public void setId(String id) {@b@ this.id = id;@b@ }@b@@b@ private Prototype prototype;@b@ @b@ public Prototype getPrototype() {@b@ return prototype;@b@ }@b@@b@ public void setPrototype(Prototype prototype) {@b@ this.prototype = prototype;@b@ }@b@@b@@b@ public Object clone(){ @b@ try {@b@ return super.clone();@b@ } catch (CloneNotSupportedException e) {@b@ e.printStackTrace();@b@ return null;@b@ } @b@ }@b@@b@}@b@public class TestMain {@b@@b@ public static void main(String[] args) {@b@ testPrototype();@b@ }@b@ @b@ private static void testPrototype(){@b@ Prototype pro = new Prototype();@b@ pro.setName("original object");@b@ NewPrototype newObj = new NewPrototype();@b@ newObj.setId("test1");@b@ newObj.setPrototype(pro);@b@ @b@ NewPrototype copyObj = (NewPrototype)newObj.clone();@b@ copyObj.setId("testCopy");@b@ copyObj.getPrototype().setName("changed object");@b@ @b@ System.out.println("original object id:" + newObj.getId());@b@ System.out.println("original object name:" + newObj.getPrototype().getName());@b@ @b@ System.out.println("cloned object id:" + copyObj.getId());@b@ System.out.println("cloned object name:" + copyObj.getPrototype().getName());@b@ @b@ }@b@@b@}@b@@b@//结果:@b@original object id:test1@b@original object name:changed object@b@cloned object id:testCopy@b@cloned object name:changed object@b@@b@@b@实例三: 深拷贝@b@public class Prototype implements Cloneable {@b@ private String name;@b@@b@ public String getName() {@b@ return name;@b@ }@b@@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@@b@ public Object clone() {@b@ try { @b@ return super.clone();@b@ } catch (CloneNotSupportedException e) { @b@ e.printStackTrace();@b@ return null;@b@ }@b@ } @b@ @b@}@b@@b@public class NewPrototype implements Cloneable {@b@ @b@ private String id;@b@ @b@ public String getId() {@b@ return id;@b@ }@b@@b@ public void setId(String id) {@b@ this.id = id;@b@ }@b@@b@ private Prototype prototype;@b@ @b@ public Prototype getPrototype() {@b@ return prototype;@b@ }@b@@b@ public void setPrototype(Prototype prototype) {@b@ this.prototype = prototype;@b@ }@b@@b@@b@ public Object clone(){@b@ NewPrototype ret = null;@b@ try {@b@ ret = (NewPrototype)super.clone();@b@ ret.prototype = (Prototype)this.prototype.clone();@b@ return ret;@b@ } catch (CloneNotSupportedException e) {@b@ e.printStackTrace();@b@ return null;@b@ } @b@ }@b@@b@}@b@@b@public class TestMain {@b@@b@ public static void main(String[] args) {@b@ testDeepCopy();@b@ }@b@ @b@ private static void testDeepCopy(){@b@ Prototype pro = new Prototype();@b@ pro.setName("original object");@b@ NewPrototype newObj = new NewPrototype();@b@ newObj.setId("test1");@b@ newObj.setPrototype(pro);@b@ @b@ NewPrototype copyObj = (NewPrototype)newObj.clone();@b@ copyObj.setId("testCopy");@b@ copyObj.getPrototype().setName("changed object");@b@ @b@ System.out.println("original object id:" + newObj.getId());@b@ System.out.println("original object name:" + newObj.getPrototype().getName());@b@ @b@ System.out.println("cloned object id:" + copyObj.getId());@b@ System.out.println("cloned object name:" + copyObj.getPrototype().getName());@b@ @b@ }@b@@b@}@b@@b@//结果:@b@original object id:test1@b@original object name:original object@b@cloned object id:testCopy@b@cloned object name:changed object@b@@b@//实例四: 利用串行化来做深复制@b@//把对象写道流里的过程是串行化(Serilization)过程;把对象从流中读出来是并行化(Deserialization)过程. 写在流里的是对象的一个拷贝,然后再从流里读出来重建对象.@b@public class PrototypeSe implements Serializable {@b@@b@ private String name;@b@@b@ public String getName() {@b@ return name;@b@ }@b@@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@@b@}@b@@b@public class NewPrototypeSe implements Serializable {@b@ @b@ private String id;@b@ @b@ public String getId() {@b@ return id;@b@ }@b@@b@ public void setId(String id) {@b@ this.id = id;@b@ }@b@@b@ private PrototypeSe prototype;@b@ @b@ public PrototypeSe getPrototype() {@b@ return prototype;@b@ }@b@@b@ public void setPrototype(PrototypeSe prototype) {@b@ this.prototype = prototype;@b@ }@b@ @b@ public Object deepClone(){@b@ try {@b@ ByteArrayOutputStream bo = new ByteArrayOutputStream();@b@ ObjectOutputStream oo = new ObjectOutputStream(bo); @b@ oo.writeObject(this); @b@ @b@ ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());@b@ ObjectInputStream oi = new ObjectInputStream(bi);@b@ return oi.readObject(); @b@ } catch (IOException | ClassNotFoundException e) {@b@ e.printStackTrace();@b@ return null;@b@ }@b@ }@b@@b@}@b@@b@public class TestDeepClone {@b@@b@ public static void main(String[] args) {@b@ PrototypeSe po = new PrototypeSe();@b@ po.setName("test1");@b@ NewPrototypeSe se = new NewPrototypeSe();@b@ se.setPrototype(po);@b@ @b@ NewPrototypeSe deepClone = (NewPrototypeSe)se.deepClone();@b@ deepClone.getPrototype().setName("test2");@b@ @b@ System.out.println("original name:" + se.getPrototype().getName());@b@ System.out.println("cloned name:" + deepClone.getPrototype().getName());@b@@b@ }@b@}@b@//结果:@b@original name:test1@b@cloned name:test2
20.状态(State)模式
/**@b@* 水的状态@b@*/@b@public interface IWaterState {@b@/**@b@* 输出水的状态@b@*/@b@public void printState();@b@}@b@ @b@/**@b@* 冰水状态实现类@b@*/@b@public class IceWaterStateImpl implements IWaterState {@b@ @Override@b@ public void printState() {@b@ System.out.println("水的状态:冰水!");@b@ }@b@}@b@ @b@/**@b@* 温水状态实现类@b@*/@b@public class WarmWaterStateImpl implements IWaterState {@b@ @Override@b@ public void printState() {@b@ System.out.println("水的状态:温水!");@b@ }@b@}@b@ @b@/**@b@* 沸水状态实现类@b@*/@b@public class WasteWaterStateImpl implements IWaterState {@b@ @Override@b@ public void printState() {@b@ System.out.println("水的状态:沸水!");@b@ }@b@}@b@ @b@/**@b@* 状态上下文实现@b@*/@b@public class WaterContext {@b@ /**@b@ * 状态对象@b@ */@b@ private IWaterState state = null;@b@ /**@b@ * 设置状态对象@b@ * @param i@b@ */@b@ public void setState(int i){@b@ if(i == 0){@b@ state = new IceWaterStateImpl();@b@ System.out.println("正在加热...");@b@ }else if(i == 1){@b@ state = new WarmWaterStateImpl();@b@ System.out.println("正在加热...");@b@ }else if(i == 2){@b@ state = new WasteWaterStateImpl();@b@ System.out.println("加热完成!");@b@ }@b@ }@b@ /**@b@ * 获得状态对象@b@ * @return@b@ */@b@ public IWaterState getState(){@b@ return state;@b@ }@b@}@b@ @b@/**@b@* 测试Main方法@b@*/@b@public class TestMain {@b@ public static void main(String [] args){@b@ IWaterState state = null;@b@ for(int i=0;i<3;i++){@b@ try {@b@ WaterContext context = new WaterContext();@b@ context.setState(i);@b@ state = context.getState();@b@ state.printState();@b@ Thread.sleep(1000);@b@ } catch (InterruptedException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ }@b@}
21.策略(Strategy)模式
public interface Strategy { @b@ public void operate(); @b@} @b@@b@public class BackDoor implements IStrategy { @b@ @Override @b@ public void operate() { @b@ System.out.println("找乔国老帮忙,让吴国太给孙权施加压力,使孙权不能杀刘备"); @b@ } @b@} @b@@b@public class GivenGreenLight implements IStrategy { @b@ @Override @b@ public void operate() { @b@ System.out.println("求吴国太开个绿灯,放行"); @b@ } @b@} @b@@b@public class BlackEnemy implements IStrategy { @b@ @Override @b@ public void operate() { @b@ System.out.println("孙夫人断后,挡住追兵"); @b@ } @b@} @b@@b@public class Context { @b@ private Strategy strategy; @b@ //构造函数,要你使用哪个妙计 @b@ public Context(Strategy strategy){ @b@ this.strategy = strategy; @b@ } @b@ public void setStrategy(Strategy strategy){ @b@ this.strategy = strategy; @b@ } @b@ public void operate(){ @b@ this.strategy.operate(); @b@ } @b@} @b@@b@public class Zhaoyun { @b@ @b@ public static void main(String[] args) { @b@ Context context; @b@ @b@ System.out.println("----------刚到吴国使用第一个锦囊---------------"); @b@ context = new Context(new BackDoor()); @b@ context.operate(); @b@ System.out.println("\n"); @b@ @b@ System.out.println("----------刘备乐不思蜀使用第二个锦囊---------------"); @b@ context.setStrategy(new GivenGreenLight()); @b@ context.operate(); @b@ System.out.println("\n"); @b@ @b@ System.out.println("----------孙权的追兵来了,使用第三个锦囊---------------"); @b@ context.setStrategy(new BlackEnemy()); @b@ context.operate(); @b@ System.out.println("\n"); @b@ } @b@ }
22.模板方法(Template Method)模式
public abstract class AbstractTemplate {@b@ private String name;@b@ public AbstractTemplate(String name){@b@ this.name = name;@b@ }@b@ public void question(){@b@ System.out.print(name + ":1 + 1 = ");@b@ System.out.print(answer());@b@ System.out.println();@b@ }@b@ public abstract int answer();@b@}@b@@b@public class StudentATemplate extends AbstractTemplate{@b@ @Override@b@ public int answer() {@b@ return 2;@b@ }@b@ public StudentATemplate(String name) {@b@ super(name);@b@ }@b@}@b@@b@public class StudentBTemplate extends AbstractTemplate{@b@ public StudentBTemplate(String name) {@b@ super(name);@b@ }@b@ @Override@b@ public int answer() {@b@ return 3;@b@ }@b@}@b@@b@@b@@Test@b@public void templatePatternTest(){@b@ AbstractTemplate aTempate = new StudentATemplate("小红");@b@ AbstractTemplate bTempate = new StudentBTemplate("小明");@b@ aTempate.question();@b@ bTempate.question();@b@}
23.访问者(Visitor)模式
abstract class Element { @b@ public abstract void accept(IVisitor visitor); @b@ public abstract void doSomething(); @b@} @b@@b@class ConcreteElement1 extends Element { @b@ public void doSomething(){ @b@ System.out.println("这是元素1"); @b@ } @b@ @b@ public void accept(IVisitor visitor) { @b@ visitor.visit(this); @b@ } @b@} @b@ @b@class ConcreteElement2 extends Element { @b@ public void doSomething(){ @b@ System.out.println("这是元素2"); @b@ } @b@ @b@ public void accept(IVisitor visitor) { @b@ visitor.visit(this); @b@ } @b@} @b@@b@interface IVisitor { @b@ public void visit(ConcreteElement1 el1); @b@ public void visit(ConcreteElement2 el2); @b@} @b@@b@class Visitor implements IVisitor { @b@ @b@ public void visit(ConcreteElement1 el1) { @b@ el1.doSomething(); @b@ } @b@ @b@ public void visit(ConcreteElement2 el2) { @b@ el2.doSomething(); @b@ } @b@} @b@@b@class ObjectStruture { @b@ public static List<Element> getList(){ @b@ List<Element> list = new ArrayList<Element>(); @b@ Random ran = new Random(); @b@ for(int i=0; i<10; i++){ @b@ int a = ran.nextInt(100); @b@ if(a>50){ @b@ list.add(new ConcreteElement1()); @b@ }else{ @b@ list.add(new ConcreteElement2()); @b@ } @b@ } @b@ return list; @b@ } @b@} @b@@b@public class Client { @b@ public static void main(String[] args){ @b@ List<Element> list = ObjectStruture.getList(); @b@ for(Element e: list){ @b@ e.accept(new Visitor()); @b@ } @b@ } @b@}