本文出自 “Changes we need ! ” 博客,请务必保留此出处http://shenzhenchufa.blog.51cto.com/730213/161581
一个程序员对设计模式的理解:
“不懂”为什么要把很简单的东西搞得那么复杂。后来随着软件开发经验的增加才开始明白我所看到的“复杂”恰恰就是设计模式的精髓所在,我所理解的“简单”就是一把钥匙开一把锁的模式,目的仅仅是着眼于解决现在的问题,而设计模式的“复杂”就在于它是要构造一个“万能钥匙”,目的是提出一种对所有锁的开锁方案。在真正理解设计模式之前我一直在编写“简单”的代码.
这个“简单”不是功能的简单,而是设计的简单。简单的设计意味着缺少灵活性,代码很钢硬,只在这个项目里有用,拿到其它的项目中就是垃圾,我将其称之为“一次性代码”。
1 public class Duck{ 2 public void quack(){ //呱呱叫 3 System.out.println("呱呱叫"); 4 } 5 public void swim(){ //游泳 6 System.out.println(" 游泳"); 7 } 8 public abstratact void display(); /*因为外观不一样,让子类自己去决定了。*/ 9 }
1 //野鸭 2 public class MallardDuck extends Duck{ 3 public void display(){ 4 System.out.println("野鸭的颜色..."); 5 } 6 } 7 //红头鸭 8 public class RedheadDuck extends Duck{ 9 public void display(){ 10 System.out.println("红头鸭的颜色..."); 11 } 12 }
1 public class Duck{ 2 public void quack(){ //呱呱叫 3 System.out.println("呱呱叫"); 4 } 5 public void swim(){ //游泳 6 System.out.println(" 游泳"); 7 } 8 public abstract void display(); /*因为外观不一样,让子类自己去决定了。*/ 9 public void fly(){ 10 System.out.println("飞吧!鸭子"); 11 } 12 }
1 //残废鸭 2 public class DisabledDuck extends Duck{ 3 public void display(){ 4 System.out.println("残废鸭的颜色..."); 5 } 6 public void fly(){ 7 //覆盖,变成什么事都不做。 8 } 9 }
1 public class Duck{ 2 public void swim(){ //游泳 3 System.out.println(" 游泳"); 4 } 5 public abstract void display(); /*因为外观不一样,让子类自 己去决定了。*/ 6 }
1 //野鸭 2 public class MallardDuck extends Duck implements Flyable,Quackable{ 3 public void display(){ 4 System.out.println("野鸭的颜色..."); 5 } 6 public void fly(){ 7 //实现该方法 8 } 9 public void quack(){ 10 //实现该方法 11 } 12 } 13 //红头鸭 14 public class RedheadDuck extends Duck implements Flyable,Quackable{ 15 public void display(){ 16 System.out.println("红头鸭的颜色..."); 17 } 18 public void fly(){ 19 //实现该方法 20 } 21 public void quack(){ 22 //实现该方法 23 } 24 } 25 //残废鸭 只实现Quackable(能叫不能飞) 26 public class DisabledDuck extends Duck implements Quackable{ 27 public void display(){ 28 System.out.println("残废鸭的颜色..."); 29 } 30 public void quack(){ 31 //实现该方法 32 } 33 }
1 public interface FlyBehavior{ 2 public void fly(); 3 } 4 public interface QuackBehavior{ 5 public void quack(); 6 }
1 public class FlyWithWings implements FlyBehavior{ 2 public void fly(){ 3 //实现了所有有翅膀的鸭子飞行行为。 4 } 5 } 6 public class FlyNoWay implements FlyBehavior{ 7 8 public void fly(){ 9 //什么都不做,不会飞 10 } 11 }
1 public class Quack implements QuackBehavior{ 2 public void quack(){ 3 //实现呱呱叫的鸭子 4 } 5 } 6 7 public class Squeak implements QuackBehavior{ 8 public void quack(){ 9 //实现吱吱叫的鸭子 10 } 11 } 12 13 public class MuteQuack implements QuackBehavior{ 14 public void quack(){ 15 //什么都不做,不会叫 16 } 17 }
1 public class Duck{ --------->在抽象类中,声明各接口,定义各接口对应的方法. 2 FlyBehavior flyBehavior;//接口 3 QuackBehavior quackBehavior;//接口 4 public Duck(){} 5 public abstract void display(); 6 public void swim(){ 7 //实现游泳的行为 8 } 9 public void performFly(){ 10 flyBehavior.fly(); -->由于是接口,会根据继承类实现的方式,而调用相应的方法. 11 } 12 public void performQuack(){ 13 quackBehavior.quack(); 14 } 15 }
1 public class Duck{ 2 FlyBehavior flyBehavior;//接口 3 QuackBehavior quackBehavior;//接口 4 public void setFlyBehavior(FlyBehavior flyBehavior){ 5 this.flyBehavior = flyBehavior; 6 } 7 public void setQuackBehavior(QuackBehavior quackBehavior { 8 this.quackBehavior= quackBehavior; 9 } 10 }
1 public class Singleton { 2 private static Singleton s; 3 public static Singleton getInstance() { 4 if (s == null) 5 s = new Singleton(); 6 return s; 7 } 8 } 9 // 测试类 10 class singletonTest { 11 public static void main(String[] args) { 12 Singleton s1 = Singleton.getInstance(); 13 Singleton s2 = Singleton.getInstance(); 14 if (s1==s2) 15 System.out.println("s1 is the same instance with s2"); 16 else 17 System.out.println("s1 is not the same instance with s2"); 18 } 19 }
1 class Singleton { 2 static boolean instance_flag = false; // true if 1 instance 3 public Singleton() { 4 if (instance_flag) 5 throw new SingletonException("Only one instance allowed"); 6 else 7 instance_flag = true; // set flag for 1 instance 8 } 9 }
1 Subject代码: 2 public interface Subject{ 3 public void attach(Observer o); 4 public void detach(Observer o); 5 public void notice(); 6 } 7 Observer代码: 8 public interface Observer{ 9 public void update(); 10 } 11 Teacher代码; 12 import java.util.Vector; 13 public class Teacher implements Subject{ 14 private String phone; 15 private Vector students; 16 public Teacher(){ 17 phone = ""; 18 students = new Vector(); 19 } 20 public void attach(Observer o){ 21 students.add(o); 22 } 23 public void detach(Observer o){ 24 students.remove(o); 25 } 26 public void notice(){ 27 for(int i=0;i<students.size();i++) 28 ((Observer)students.get(i)).update(); 29 } 30 public void setPhone(String phone){ 31 this.phone = phone; 32 notice(); --关键 33 } 34 public String getPhone(){ 35 return phone; 36 } 37 } 38 Student代码: 39 public class Student implements Observer{ 40 private String name; 41 private String phone; 42 private Teacher teacher; 43 public Student(String name,Teacher t){ 44 this.name = name; 45 teacher = t; 46 } 47 public void show(){ 48 System.out.println("Name:"+name+"\nTeacher'sphone:"+phone); 49 } 50 public void update(){ 51 phone = teacher.getPhone(); 52 } 53 } 54 Client代码: 55 package observer; 56 import java.util.Vector; 57 public class Client{ -->可以只定义目标者,观察者,另外的vector,只为了输入结果. 58 public static void main(String[] args){ 59 Vector students = new Vector(); 60 Teacher t = new Teacher(); 61 for(int i= 0 ;i<10;i++){ 62 Student st = new Student("lili"+i,t); 63 students.add(st); 64 t.attach(st); 65 } 66 t.setPhone("88803807"); 67 for(int i=0;i<10;i++) 68 ((Student)students.get(i)).show(); 69 t.setPhone("88808880"); 70 for(int i=0;i<10;i++) 71 ((Student)students.get(i)).show(); 72 } 73 }
1 Iterator接口: 2 package iterator; 3 public interface Iterator{ 4 /* 5 Item:即是集合中的各对象的类型.若为String,即把所有的ITEM改为String,若为其它自定义的类,则改为各自定义的类 6 的接口,或类. --->important. 7 */ 8 public Item first(); 9 public Item next(); 10 public boolean isDone(); 11 public Item currentItem(); 12 } 13 Controller类实现了Iterator接口。 14 package iterator; 15 import java.util.Vector; 16 public class Controller implements Iterator{ 17 private int current =0; 18 Vector channel; 19 public Controller(Vector v){ 20 channel = v; 21 } 22 public Item first(){ 23 current = 0; 24 return (Item)channel.get(current); 25 } 26 public Item next(){ 27 current ++; 28 return (Item)channel.get(current); 29 } 30 public Item currentItem(){ 31 return (Item)channel.get(current); 32 } 33 public boolean isDone(){ 34 return current>= channel.size()-1; 35 } 36 } 37 Television接口: 38 package iterator; 39 import java.util.Vector; 40 public interface Television{ 41 public Iterator createIterator(); 42 } 43 HaierTV类实现了Television接口。 44 package iterator; 45 import java.util.Vector; 46 public class HaierTV implements Television{ ---对象 47 private Vector channel; 48 public HaierTV(){ 49 channel = new Vector(); 50 channel.addElement(new Item("channel 1")); --各元素,用VECTOR存放 51 channel.addElement(new Item("channel 2")); 52 channel.addElement(new Item("channel 3")); 53 channel.addElement(new Item("channel 4")); 54 channel.addElement(new Item("channel 5")); 55 channel.addElement(new Item("channel 6")); 56 channel.addElement(new Item("channel 7")); 57 } 58 public Iterator createIterator(){ 59 return new Controller(channel); --把这个VECTOR放到迭代器中构造方法中去 60 } 61 } 62 Client客户端: 63 package iterator; 64 public class Client{ 65 public static void main(String[] args){ 66 Television tv = new HaierTV(); 67 Iterator it =tv.createIterator(); 68 System.out.println(it.first().getName()); 69 while(!it.isDone()){ 70 System.out.println(it.next().getName()); 71 } 72 } 73 } 74 Item类的接口: 75 package iterator; 76 public class Item{ 77 private String name; 78 public Item(String aName){ 79 name = aName; 80 } 81 public String getName(){ 82 return name; 83 } 84 }
1 public class TeaCup{.....} 2 public class TeaBag{.....} 3 public class Water{.....} 4 public class FacadeCuppaMaker{ 5 private boolean TeaBagIsSteeped; 6 public FacadeCuppaMaker(){ 7 System.out.println("FacadeCuppaMaker 准备好冲茶了"); 8 } 9 public TeaCup makeACuppa(){ 10 TeaCup cup = new TeaCup(); 11 TeaBag teaBag= new TeaBag(); 12 Water water = new Water(); 13 cup.addFacadeTeaBag(teaBag); 14 water.boilFacadeWater(); 15 cup.addFacadeWater(water); 16 cup.steepTeaBag(); 17 return cup; 18 } 19 }
public class Adaptee{ public long getPower(long base,long exp){ long result=1; for(int i=0;i<exp;i++) result*=base; return result; } } 目标类:--也可直接实现,不用接口。 public interface Target{ public long get2Power(long exp); } public class Adapter implements Target{ private Adaptee pt; public Adapter(){ pt = new Adaptee(); } public long get2Power(long exp){ return pt.getPower(2,exp); ---修改原来方法中的参数, } }
1 public boolean updateRecordStates(Double recordId,Double tableNameMapping,int state,boolean 2 subRecordUpdate) throws RemoteException; 3 已有实现类: 4 public boolean updateRecordStates(Double recordId,Double tableNameMapping,int state,boolean 5 subRecordUpdate) throws RemoteException 6 { 7 return moveTable.updateRecordStates(recordId,tableNameMapping,state,subRecordUpdate); 8 } 9 若采用适配器模式: 10 接口: 11 public boolean updateStatesAdapterForSelfPanel(Double recordId,Double tableNameMapping,int state) 12 throws RemoteException; 13 实现类: 14 public boolean updateStatesAdapterForSelfPanel(Double recordId,Double tableNameMapping,int state) 15 throws RemoteException 16 { 17 return this.updateRecordStates(recordId,tableNameMapping,state,false); 18 }
1 //抽象角色: 2 abstract public class Subject 3 { 4 abstract public void request(); 5 } 6 //真实角色: 7 public class RealSubject extends Subject 8 { 9 public void request() 10 { 11 System.out.println("From real subject."); 12 } 13 } 14 //代理角色: 15 public class ProxySubject extends Subject 16 { 17 private RealSubject realSubject; //以真实角色作为代理角色的属性 18 public ProxySubject() 19 { realSubject=new RealSubject(); } 20 public void request() //与原方法名相同 21 { 22 preRequest(); 23 realSubject.request(); //此处执行真实对象的request方法 24 postRequest(); 25 } 26 private void preRequest() 27 { 28 //something you want to do before requesting 29 } 30 private void postRequest() 31 { 32 //something you want to do after requesting 33 } 34 } 35 //客户端调用: 36 Subject sub=new ProxySubject(); 37 Sub.request();
1 public interface Subject 2 { 3 public void request(); 4 }
1 //代理角色: 2 import java.lang.reflect.Method; 3 import java.lang.reflect.InvocationHandler; 4 public class DynamicSubject implements InvocationHandler { 5 private Object sub; 6 public DynamicSubject(Object obj) { 7 sub = obj; 8 } 9 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 10 System.out.println("before calling " + method); 11 method.invoke(sub,args); 12 System.out.println("after calling " + method); 13 return null; 14 } 15 } 16 ==> 17 method.invoke(sub,args);
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Client { static public void main(String[] args) throws Throwable { RealSubject rs = new RealSubject(); //在这里指定被代理类 InvocationHandler ds = new DynamicSubject(rs); //初始化代理类 Subject subject = (Subject) Proxy.newProxyInstance(rs.getClass().getClassLoader(),rs.getClass ().getInterfaces(),ds ); subject.request(); }
1 package dynamicProxy; 2 public interface Work { 3 public void startWork(); 4 } 5 package dynamicProxy; 6 public class JasonWork implements Work { 7 public void startWork() { 8 System.out.println("jason start to work..."); 9 } 10 } 11 public interface Play { 12 public void startPlay(); 13 } 14 public class JasonPlay implements Play { 15 public void startPlay() { 16 System.out.println("jason start to play..."); 17 } 18 } 19 public class Test { 20 public static void main(String[] args) 21 { 22 JasonWork work=new JasonWork(); 23 InvocationHandler dynamicProxy=new DynamicProxy(work); 24 Work jasonproxy=(Work)Proxy.newProxyInstance(work.getClass().getClassLoader(), 25 work.getClass().getInterfaces(), dynamicProxy); 26 jasonproxy.startWork(); 27 JasonPlay play=new JasonPlay(); 28 InvocationHandler dynamicProxy=new DynamicProxy(play); 29 Play jasonproxy=(Play)Proxy.newProxyInstance(play.getClass().getClassLoader(), 30 play.getClass().getInterfaces(), dynamicProxy); 31 jasonproxy.startPlay(); 32 } 33 }
1 public interface Color { 2 public void show(); 3 } 4 package state; 5 class Light 6 { 7 Color color; 8 public Color getColor() { 9 return color; 10 } 11 public void setColor(Color color) { 12 this.color = color; 13 } 14 15 public Light() 16 { 17 color=new RedColor(this); 18 } 19 20 public void showColor() 21 { 22 color.show(); 23 } 24 25 } 26 class RedColor implements Color 27 { 28 Light light; 29 public RedColor(Light light) 30 { 31 this.light=light; 32 } 33 34 public void show() 35 { 36 System.out.println("the color is red,the car must stop !"); 37 System.out.println("write down all logic shoud do this in this state....."); 38 light.setColor(new GreenColor(light)); 39 } 40 } 41 class GreenColor implements Color 42 { 43 Light light; 44 public GreenColor(Light light) 45 { 46 this.light=light; 47 } 48 49 public void show() 50 { 51 System.out.println("the color is green,the car can run !"); 52 System.out.println("write down all logic shoud do this in this state....."); 53 light.setColor(new YellowColor(light)); 54 } 55 } 56 class YellowColor implements Color 57 { 58 Light light; 59 public YellowColor(Light light) 60 { 61 this.light=light; 62 } 63 64 public void show() 65 { 66 System.out.println("the color is yellow,the car shoud stop !"); 67 System.out.println("write down all logic shoud do this in this state....."); 68 light.setColor(new RedColor(light)); 69 } 70 } 71 public class CarLight { 72 public static void main(String[] args) { 73 Light light=new Light(); 74 75 //初始调用为红灯 76 light.showColor(); 77 //再调用为绿灯 78 light.showColor(); 79 //再调用为黄灯 80 light.showColor(); 81 //不断调用,不断循环. 82 } 83 } 84
1 public interface Car { 2 public void showCarName(); 3 } 4 class BMWCar implements Car 5 { 6 public void showCarName() 7 { 8 System.out.println("this is the BMWCar ."); 9 } 10 } 11 class FordCar implements Car 12 { 13 public void showCarName() 14 { 15 System.out.println("this is the FordCar ."); 16 } 17 } 18 class CarFactory 19 { 20 public static Car car; 21 public static Car getCar(String name) 22 { 23 if("BMW".equals(name)) 24 { 25 car = new BMWCar(); 26 } 27 if("Ford".equals(name)) 28 { 29 car = new FordCar(); 30 } 31 return car; 32 } 33 } 34 class CarFlyWeightFactory 35 { 36 public Car car; 37 private Hashtable<String,Car> carPool=new Hashtable<String,Car>(); 38 public Car getCar(String name) 39 { 40 if("BMW".equals(name)) 41 { 42 car=carPool.get(name); 43 if(car==null) 44 { 45 car=new BMWCar(); 46 carPool.put(name, car); 47 } 48 } 49 50 if("Ford".equals(name)) 51 { 52 car=carPool.get(name); 53 if(car==null) 54 { 55 car=new FordCar(); 56 carPool.put(name, car); 57 } 58 } 59 return car; 60 } 61 public int getNumber(){ return carPool.getSize(); } 62 } 63 64 public class Test { 65 public static void main(String[] args) { 66 CarFlyWeightFactory carFlyWeightFactory=new CarFlyWeightFactory(); 67 Car carf1=carFlyWeightFactory.getCar("Ford"); 68 carf1.showCarName(); 69 Car carf2=carFlyWeightFactory.getCar("Ford"); 70 carf2.showCarName(); 71 if(carf1==carf2) 72 { 73 System.out.println("同一部车来的"); 74 } 75 else 76 { 77 System.out.println("不同一部车来的"); 78 } 79 System.out.println("车的数量是:"+carFlyWeightFactory.getNumber()); 80 } 81 }
1 public class Boy { 2 3 private boolean hasCar; // 是否有车 4 private boolean hasHouse; // 是否有房 5 private boolean hasResponsibility; // 是否有责任心 6 public Boy() { 7 } 8 public Boy(boolean hasCar, boolean hasHouse, boolean hasResponsibility) { 9 this.hasCar = hasCar; 10 this.hasHouse = hasHouse; 11 this.hasResponsibility = hasResponsibility; 12 } 13 public boolean isHasCar() { 14 return hasCar; 15 } 16 public void setHasCar(boolean hasCar) { 17 this.hasCar = hasCar; 18 } 19 public boolean isHasHouse() { 20 return hasHouse; 21 } 22 public void setHasHouse(boolean hasHouse) { 23 this.hasHouse = hasHouse; 24 } 25 public boolean isHasResponsibility() { 26 return hasResponsibility; 27 } 28 public void setHasResponsibility(boolean hasResponsibility) { 29 this.hasResponsibility = hasResponsibility; 30 } 31 } 32 public interface Handler { 33 public void handleRequest(Boy boy); 34 } 35 public class HouseHandler implements Handler { 36 37 private Handler handler; 38 public HouseHandler(Handler handler) { 39 this.handler = handler; 40 } 41 public Handler getHandler() { 42 return handler; 43 } 44 public void setHandler(Handler handler) { 45 this.handler = handler; 46 } 47 public void handleRequest(Boy boy) { 48 if (boy.isHasHouse()) { 49 System.out.println("没想到吧,我还有房子"); 50 } else { 51 System.out.println("我也没有房"); 52 handler.handleRequest(boy); 53 } 54 } 55 } 56 public class CarHandler implements Handler { 57 private Handler handler; 58 public CarHandler(Handler handler) { 59 this.handler = handler; 60 } 61 public Handler getHandler() { 62 return handler; 63 } 64 public void setHandler(Handler handler) { 65 this.handler = handler; 66 } 67 public void handleRequest(Boy boy) { 68 if (boy.isHasCar()) { 69 System.out.println("呵呵,我有辆车"); 70 } else { 71 System.out.println("我没有车"); 72 handler.handleRequest(boy); 73 } 74 } 75 } 76 public class ResponsibilityHandler implements Handler { 77 private Handler handler; 78 public ResponsibilityHandler(Handler handler) { 79 this.handler = handler; 80 } 81 public Handler getHandler() { 82 return handler; 83 } 84 public void setHandler(Handler handler) { 85 this.handler = handler; 86 } 87 public void handleRequest(Boy boy) { 88 if (boy.isHasResponsibility()) { 89 System.out.println("我只有一颗带Responsibility的心"); 90 } else { 91 System.out.println("更没有责任心"); 92 handler.handleRequest(boy); 93 } 94 } 95 } 96 public class Girl { 97 98 public static void main(String[] args) { 99 // 这个boy没有车,也没有房,不过很有责任心 100 Boy boy = new Boy(false, false, true); 101 // 也可以使用setHanlder方法 102 Handler handler = new CarHandler(new HouseHandler( 103 new ResponsibilityHandler(null))); 104 handler.handleRequest(boy); 105 } 106 }
1 package memento; 2 public class Memento{ 3 String name; 4 int age; 5 public Memento(String name,int age){ 6 this.name = name; 7 this.age = age; 8 } 9 } 10 //Employee模式: 11 package memento; 12 public class Employee{ 13 private String name; 14 private int age; 15 public Employee(String aName,int aAge){ 16 name = aName; 17 age = aAge; 18 } 19 public void setName(String aName){ 20 name = aName; 21 } 22 public void setAge(int aAge){ 23 age = aAge; 24 } 25 public Memento saveMemento(){ 26 return new Memento(name,age); 27 } 28 public void restoreMemento(Memento memento){ 29 age = memento.age; 30 name = memento.name; 31 } 32 public int getAge(){ 33 return age; 34 } 35 public String getName(){ 36 return name; 37 } 38 } 39 //CareTaker代码: 40 package memento; 41 import java.util.Vector; 42 public class CareTaker{ 43 private Vector v; 44 private int current; 45 public CareTaker(){ 46 current = -1; 47 v = new Vector(); 48 } 49 public void setMemento(Memento mem){ 50 current ++; 51 v.add(mem); 52 } 53 public Memento getMemento(){ 54 if(current>0){ 55 current --; 56 return(Memento) v.get(current); 57 } 58 return null; 59 } 60 } 61 //Client代码: 62 package memento; 63 public class Client{ 64 public static void show(Employee e){ 65 System.out.println("-----------------------------------"); 66 System.out.println("Name:"+e.getName()); 67 System.out.println("Age:" + e.getAge()); 68 System.out.println("-----------------------------------"); 69 } 70 public static void main(String[] args){ 71 Employee e = new Employee("lili",25); 72 CareTaker ct = new CareTaker(); 73 show(e); 74 ct.setMemento(e.saveMemento()); 75 e.setName("litianli"); 76 show(e); 77 ct.setMemento(e.saveMemento()); 78 e.setAge(45); 79 show(e); 80 ct.setMemento(e.saveMemento()); 81 //restore 82 e.restoreMemento(ct.getMemento()); 83 show(e); 84 e.restoreMemento(ct.getMemento()); 85 show(e); 86 } 87 }