常见设计模式介绍
1.单例模式(singleton)
有些时候,允许自由创建某个类的实例没有意义,还可能造成系统性能下降。如果一个类始终只能创建一个实例,则这个类被称为单例类,这种模式被称为单例模式。
1 public class Singleton{ 2 3 public static void main(String[] args) 4 { 5 ///创建Singleton对象不能通过构造器,只能通过getInstance方法 6 Singleton s1 = Singleton.getInstance(); 7 Singleton s2 = Singleton.getInstance(); 8 ///将输出true 9 System.out.println(s1 == s2) 10 } 11 12 ///使用一个变量来缓存曾经创建的实例 13 private static Singleton instance; 14 ///将构造器使用private修饰,隐藏该构造器 15 private Singleton(){ 16 System.out.println("Singleton被构造!"); 17 } 18 19 ///提供一个静态方法,用于返回Singleton实例 20 ///该方法可以加入自定义的控制,保证只产生一个Singleton对象 21 public static Singleton getInstance() 22 { 23 ///如果instance为null,表明还不曾创建Singleton对象 24 ///如果instance不为null,则表明已经创建了Singleton对象,将不会执行该方法 25 if(instance == null) 26 { 27 ///创建一个Singleton对象,并将其缓存起来 28 instance = new Singleton(); 29 } 30 return instance; 31 } 32 33 }
单例模式主要有如下两个优势:
(1)减少创建Java实例所带来的系统开销
(2)便于系统跟踪单个Java实例的生命周期、实力状态等。
2.简单工厂(Static Factory Method)
简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
A实例调用B实例的方法,称为A依赖于B。如果实用new关键字来创建一个B实例(硬编码耦合),然后调用B实例的方法。一单系统需要重构:需要使用C类来代替B类时,程序不得不改写A类代码。而用工厂模式则不需要关心B对象的实现、创建过程。
Output,接口
1 public interface Output 2 { 3 ///接口里定义的属性只能是常量 4 int MAX_CACHE_LINE = 50; 5 ///接口里定义的只能是public的抽象实例方法 6 void out(); 7 void getData(String msg); 8 }
Printer, Output的一个实现
1 ///让Printer类实现Output 2 public class Printer implements Output 3 { 4 private String[] printData = new String[MAX_CACHE_LINE]; 5 ///用以记录当前需打印的作业数 6 private int dataNum = 0; 7 public void out() 8 { 9 ///只要还有作业,继续打印 10 while(dataNum > 0) 11 { 12 System.out.println("打印机打印:" + printData[0]); 13 ///把作业队列整体迁移一位,并将剩下的作业数减1 14 System.arraycopy(printData, 1, printData, 0, --dataNum); 15 } 16 } 17 public void getData(String msg) 18 { 19 if(dataNum >= MAX_CACHE_LINE) 20 { 21 System.out.println("输出队列已满,添加失败"); 22 } 23 else 24 { 25 ///把打印数据添加到队列里,已保存数据的数量加1 26 printData[dataNum++] = msg; 27 } 28 } 29 }
BetterPrinter, Output的一个实现
1 public class BetterPrinter implements Output 2 { 3 private String[] printData = new String[MAX_CACHE_LINE * 2]; 4 ///用以记录当前需打印的作业数 5 private int dataNum = 0; 6 public void out() 7 { 8 ///只要还有作业,继续打印 9 while(dataNum > 0) 10 { 11 System.out.println("高速打印机正在打印:" + printData[0]); 12 ///把作业队列整体前移一位,并将剩下的作业数减1 13 System.arraycopy(printData, 1, printData, 0, --dataNum); 14 } 15 16 } 17 18 public void getData(String msg) 19 { 20 if(dataNum >= MAX_CACHE_LINE * 2) 21 { 22 System.out.println("输出队列已满,添加失败"); 23 } 24 else 25 { 26 ///把打印数据添加到队列里,已保存数据的数量加1 27 printData[dataNum++] = msg; 28 } 29 } 30 }
OutputFactory,简单工厂类
1 public Output getPrinterOutput(String type){ 2 if(type.equalsIgnoreCase("better")){ 3 return new BetterPrinter(); 4 } 5 else { 6 return new Printer(); 7 } 8 }
Computer
1 public class Computer 2 { 3 private Output out; 4 5 public Computer(Output out) 6 { 7 this.out = out; 8 } 9 ///定义一个模拟获取字符串输入的方法 10 public void keyIn(String msg) 11 { 12 out.getData(msg); 13 } 14 ///定义一个模拟打印的方法 15 public void print() 16 { 17 out.out(); 18 } 19 public static void main(String[] args) 20 { 21 ///创建OutputFactory 22 OutputFactory of = new OutputFactory(); 23 ///将Output对象传入,创建Computer对象 24 Computer c = new Computer(of.getPrinterOutput("normal")); 25 c.keyIn("建筑永恒之道"); 26 c.keyIn("建筑模式语言"); 27 c.print(); 28 29 c = new Computer(of.getPrinterOutput("better")); 30 c.keyIn("建筑永恒之道"); 31 c.keyIn("建筑模式语言"); 32 c.print(); 33 34 } 35 36 }
使用简单工厂模式的优势:让对象的调用者和对象创建过程分离,当对象调用者需要对象时,直接向工厂请求即可。从而避免了对象的调用者与对象的实现类以硬编码方式耦合,以提高系统的可维护性、可扩展性。工厂模式也有一个小小的缺陷:当产品修改时,工厂类也要做相应的修改。
3.工厂方法(Factory Method)和抽象工厂(Abstract Factory)
如果我们不想再工厂类中进行逻辑判断,程序可以为不同产品类提供不同的工厂,不同的工厂类生产不同的产品。
当使用工厂方法设计模式时,对象调用者需要与具体的工厂类耦合,如:
1 ///工厂类的定义1 2 public class BetterPrinterFactory 3 implements OutputFactory 4 { 5 public Output getOutput() 6 { 7 ///该工厂只负责生产BetterPrinter对象 8 return new BetterPrinter(); 9 } 10 } 11 ///工厂类的定义2 12 public class PrinterFactory 13 implements OutputFactory 14 { 15 public Output getOutput() 16 { 17 ///该工厂只负责生产Printer对象 18 return Printer(); 19 } 20 } 21 ///工厂类的调用 22 OutputFactory of = new PrinterFactory(); 23 Computer c = new Computer(of.getOutput());
使用简单工厂类,需要在工厂类里做逻辑判断。而工厂类虽然不用再工厂类做判断。但是带来了另一种耦合:客户端代码与不同的工厂类耦合。
为了解决客户端代码与不同工厂类耦合的问题。在工厂类的基础上再增加一个工厂类,该工厂类不制造具体的被调用对象,而是制造不同工厂对象。如:
1 ///抽象工厂类的定义,在工厂类的基础上再建一个工厂类 2 public class OutputFactoryFactory 3 { 4 ///仅定义一个方法用于返回输出设备 5 public static OutputFactory getOutputFactory(String type) 6 { 7 if(type.equalsIgnoreCase("better")) 8 { 9 return new BetterPrinterFactory(); 10 } 11 else 12 { 13 return new PrinterFactory(); 14 } 15 } 16 } 17 18 ///抽象工厂类的调用 19 OutputFactory of = OutputFactoryFactory.getOutputFactory("better"); 20 Computer c = new Computer(of.getOutput());
4.代理模式(Proxy)
代理模式是一种应用非常广泛的设计模式,当客户端代码需要调用某个对象时,客户端实际上不关心是否准确得到该对象,它只要一个提供该功能的对象即可,此时我们就可返回该对象的代理(Proxy)。
代理就是一个Java对象代表另一个Java对象来采取行动。如:
1 public class ImageProxy implements Image 2 { 3 ///组合一个image实例,作为被代理的对象 4 private Image image; 5 ///使用抽象实体来初始化代理对象 6 public ImageProxy(Image image) 7 { 8 this.image = image; 9 } 10 /** 11 *重写Image接口的show()方法 12 *该方法用于控制对象对被代理对象的访问, 13 *并根据需要负责创建和删除被代理对象 14 */ 15 public void show() 16 { 17 ///只有当真正需要调用image的show方法时才创建被代理对象 18 if(image == null) 19 { 20 image = new BigImage(); 21 } 22 image.show(); 23 } 24 }
调用时,先不创建:
1 Image image = new ImageProxy(null);
Hibernate默认启用延迟加载,当系统加载A实体时,A实体关联的B实体并未被加载出来,A实体所关联的B实体全部是代理对象——只有等到A实体真正需要访问B实体时,系统才会去数据库里抓取B实体所对应的记录。
借助于Java提供的Proxy和InvocationHandler,可以实现在运行时生成动态代理的功能, 而动态代理对象就可以作为目标对象使用,而且增强了目标对象的功能。如:
Panther
1 public interface Panther 2 { 3 ///info方法声明 4 public void info(); 5 ///run方法声明 6 public void run(); 7 }
GunPanther
1 public class GunPanther implements Panther 2 { 3 ///info方法实现,仅仅打印一个字符串 4 public void info() 5 { 6 System.out.println("我是一只猎豹!"); 7 } 8 ///run方法实现,仅仅打印一个字符串 9 public void run() 10 { 11 System.out.println("我奔跑迅速"); 12 } 13 }
MyProxyFactory,创建代理对象
1 public class MyProxyFactory 2 { 3 ///为指定target生成动态代理对象 4 public static Object getProxy(Object target) 5 throws Exception 6 { 7 ///创建一个MyInvokationHandler对象 8 MyInvokationHandler handler = new MyInvokationHandler(); 9 ///为MyInvokationHandler设置target对象 10 handler.setTarget(target); 11 ///创建、并返回一个动态代理 12 return Proxy.newProxyInstance(target.getClass().getClassLoader(), 13 target.getClass().getInterfaces(), handler); 14 15 } 16 }
MyInvokationHandler,增强代理的功能
1 public class MyInvokationHandler implements InvocationHandler 2 { 3 ///需要被代理的对象 4 private Object target; 5 public void setTarget(Object target) 6 { 7 this.target = target; 8 } 9 ///执行动态代理对象的所有方法时,都会被替换成执行如下的invoke方法 10 public Object invoke(Object proxy, Method method, Object[] args) 11 throws Exception 12 { 13 TxUtil tx = new TxUtil(); 14 ///执行TxUtil对象中的beginTx. 15 tx.beginTx(); 16 ///以target作为主调来执行method方法 17 Object result = method.invoke(target, args); 18 ///执行TxUtil对象中的endTx. 19 tx.endTx(); 20 return result; 21 } 22 }
TxUtil
1 public class TxUtil 2 { 3 ///第一个拦截器方法:模拟事务开始 4 public void beginTx() 5 { 6 System.out.println("====模拟开始事务==="); 7 } 8 ///第二个拦截器方法:模拟失误结束 9 public void endTx() 10 { 11 System.out.println("====模拟结束事务===="); 12 } 13 }
测试
1 public static void main(String[] args) 2 throws Exception 3 { 4 ///创建一个原始的GunDog对象,作为target 5 Panther target = new GunPanther(); 6 ///以指定的target来创建动态代理 7 Panther panther = (Panther)MyProxyFactory.getProxy(target); 8 ///调用代理对象的info()和run()方法 9 panther.info(); 10 panther.run(); 11 }
Spring所创建的AOP代理就是这种动态代理。但是Spring AOP更灵活。
5.命令模式(Command)
某个方法需要完成某一个功能,完成这个功能的大部分步骤已经确定了,但可能有少量具体步骤无法确定,必须等到执行该方法时才可以确定。(在某些编程语言如Ruby,Perl里,允许传入一个代码块作为参数。但Java暂时还不支持代码块作为参数)。在Java中,传入该方法的是一个对象,该对象通常是某个接口的匿名实现类的实例,该接口通常被称为命令接口,这种设计方式也被称为命令模式。
如:
Command
1 public interface Command 2 { 3 ///接口里定义的process方法用于封装“处理行为” 4 viod process(int[] target); 5 }
ProcessArray
1 public class ProcessArray 2 { 3 ///定义一个each()方法,用于处理数组 4 public void each(int[] target, Command cmd) 5 { 6 cmd.process(target); 7 } 8 }
TestCommand
1 public class TestCommand 2 { 3 public static void main(String[] args) 4 { 5 ProcessArray pa = new ProcessArray(); 6 int[] target = {3, -4, 6, 4}; 7 ///第一次处理数组,具体处理行为取决于Command对象 8 pa.each(target, new Command() 9 { 10 ///重写process()方法,决定具体的处理行为 11 public void process(int[] target) 12 { 13 for(int tmp:target) 14 { 15 System.out.println("迭代输出目标数组的元素:"+ tmp); 16 } 17 } 18 }); 19 System.out.println("-----------"); 20 ///第二次处理数组,具体处理行为取决于Command对象 21 pa.each(target, new Command() 22 { 23 ///重写process方法,决定具体的处理行为 24 public void process(int[] target) 25 { 26 int sum = 0; 27 for(int tmp:target) 28 { 29 sum += tmp; 30 } 31 System.out.println("数组元素的总和是:" + sum); 32 } 33 }); 34 } 35 }
HibernateTemplate使用了executeXxx()方法弥补了HibernateTemplate的不足,该方法需要接受一个HibernateCallback接口,该接口的代码如下:
1 public interface HibernateCallback 2 { 3 Object doInHibernate(Session session); 4 }
6.策略模式(Strategy)
策略模式用于封装系列的算法,这些算法通常被封装在一个被称为Context的类中,客户端程序可以自由选择其中一种算法,或让Context为客户端选择一种最佳算法——使用策略模式的优势是为了支持算法的自由切换。
DiscountStrategy,折扣方法接口
1 public interface DiscountStrategy 2 { 3 ///定义一个用于计算打折价的方法 4 double getDiscount(double orginPrice); 5 }
OldDiscount,旧书打折算法
1 public class OldDiscount implements DiscountStrategy{ 2 ///重写getDiscount()方法,提供旧书打折算法 3 public double getDiscount(double orginPrice){ 4 System.out.println("使用旧书折扣..."); 5 return originPrice * 0.7; 6 } 7 }
VipDiscount,VIP打折算法
1 ///实现DiscountStrategy接口,实现对VIP打折的算法 2 public class VipDiscount implements DiscountStrategy{ 3 ///重写getDiscount()方法,提供VIP打折算法 4 public double getDiscount(double originPrice){ 5 System.out.println("使用VIP折扣..."); 6 return originPrice * 0.5; 7 } 8 }
策略定义
1 public class DiscountContext 2 { 3 ///组合一个DiscountStrategy对象 4 private DiscountStrategy strategy; 5 ///构造器,传入一个DiscountStrategy对象 6 public DiscountContext(DiscountStrategy strategy) 7 { 8 this.strategy = strategy; 9 } 10 ///根据实际所使用的DiscountStrategy对象得到折扣价 11 public double getDiscountPrice(double price) 12 { 13 ///如果strategy为null,系统自动选择OldDiscount类 14 if(strategy == null) 15 { 16 strategy = new OldDiscount(); 17 } 18 return this.strategy.getDiscount(price); 19 } 20 ///提供切换算法的方法 21 public void setDiscount(DiscountStrategy strategy) 22 { 23 this.strategy = strategy; 24 } 25 }
测试
1 public static void main(String[] args) 2 { 3 ///客户端没有选择打折策略类 4 DiscountContext dc = new DiscountContext(null); 5 double price1 = 79; 6 ///使用默认的打折策略 7 System.out.println("79元的书默认打折后的价格是:" 8 + dc.getDiscountPrice(price1)); 9 ///客户端选择合适的VIP打折策略 10 dc.setDiscount(new VipDiscount()); 11 double price2 = 89; 12 ///使用VIP打折得到打折价格 13 System.out.println("89元的书对VIP用户的价格是:" 14 + dc.getDiscountPrice(price2)); 15 }
使用策略模式可以让客户端代码在不同的打折策略之间切换,但也有一个小小的遗憾:客户端代码需要和不同的策略耦合。为了弥补这个不足,我们可以考虑使用配置文件来指定DiscountContext使用哪种打折策略——这就彻底分离客户端代码和具体打折策略类。
7.门面模式(Facade)
随着系统的不断改进和开发,他们会变得越来越复杂,系统会生产大量的类,这使得程序流程更难被理解。门面模式可为这些类提供一个简化的接口,从而简化访问这些类的复杂性。
门面模式(Facade)也被称为正面模式、外观模式,这种模式用于将一组复杂的类包装到一个简单的外部接口中。
原来的方式
1 ///依次创建三个部门实例 2 payment pay = new PaymentImpl(); 3 Cook cook = new CookImpl(); 4 Waiter waiter = new WaiterImpl(); 5 ///依次调用三个部门实例的方法来实现用餐功能 6 String food = pay.pay(); 7 food = cook.cook(food); 8 waiter.serve(food);
门面模式
1 public class Facade{ 2 ///定义被Facade封装的三个部门 3 payment pay; 4 Cook cook; 5 Waiter waiter; 6 7 ///构造器 8 public Facade(){ 9 this.pay = new PaymentImpl(); 10 this.cook = new CookImpl(); 11 this.waiter = new WaiterImpl(); 12 } 13 14 public void serveFood(){ 15 ///依次调用三个部门的方法,封装成一个serveFood()方法 16 String food = pay.pay(); 17 food = cook.cook(food); 18 waiter.serve(food); 19 } 20 }
门面模式调用
1 Facade f = new Facade(); 2 f.serveFood();
8.桥接模式(Bridge)
由于实际的需要,某个类具有两个以上的维度变化,如果只有使用继承将无法实现这种需要,或者使得设计变得相当臃肿。而桥接模式的做法是把变化部分抽象出来,使变化部分与主类分离开来,从而将多个的变化彻底分离。
最后提供一个管理类来组合不同维度上的变化,通过这种组合来满足业务的需要。
Peppery口味风格接口:
1 public interface Peppery 2 { 3 String style(); 4 }
口味之一
1 public class PepperyStyle implements Peppery 2 { 3 ///实现“辣味”风格的方法 4 public String style() 5 { 6 return "辣味很重,很过瘾..."; 7 } 8 }
口味之二
1 public class PlainStyle implements Peppery 2 { 3 ///实现“不辣”风格的方法 4 public String style() 5 { 6 return "味道清淡,很养胃..."; 7 } 8 }
口味的桥梁
1 public abstract class AbstractNoodle 2 { 3 ///组合一个Peppery变量,用于将该维度的变化独立出来 4 protected Peppery style; 5 ///没份Noodle必须组合一个Peppery对象 6 public AbstractNoodle(Peppery style) 7 { 8 this.style = style; 9 } 10 public abstract void eat(); 11 }
材料之一,继承口味
1 public class PorkNoodle extends AbstractNoodle 2 { 3 public PorkyNoodle(Peppery style) 4 { 5 super(style); 6 } 7 ///实现eat()抽象方法 8 public void eat() 9 { 10 System.out.println("这是一碗稍嫌油腻的猪肉面条。" 11 + super.style.style()); 12 } 13 }
材料之二,继承口味
1 public class BeefMoodle extends AbstractNoodle 2 { 3 public BeefMoodle(Peppery style) 4 { 5 super(style); 6 } 7 ///实现eat() 8 { 9 System.out.println("这是一碗美味的牛肉面条。" 10 + super.style.style()); 11 } 12 }
主程序
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 ///下面将得到“辣味”的牛肉面 6 AbstractNoodle noodle1 = new BeefMoodle(new PepperyStyle()); 7 noodle1.eat(); 8 ///下面将得到“不辣”的牛肉面 9 AbstractNoodle noodle2 = new BeefMoodle(new PlainStyle()); 10 noodle2.eat(); 11 ///下面将得到“辣味”的猪肉面 12 AbstractNoodle noodle3 = new PorkyNoodle(new PepperyStyle()); 13 noodle3.eat(); 14 ///下面将得到“不辣”的猪肉面 15 AbstractNoodle noodle4 = new PorkyNoodle(new PlainStyle()); 16 noodle4.eat(); 17 } 18 }
Java EE应用中常见的DAO模式正是桥接模式的应用。
实际上,一个设计优良的项目,本身就是设计模式最好的教科书,例如Spring框架,当你深入阅读其源代码时,你会发现这个框架处处充满了设计模式的应用场景。
9.观察者模式(Observer)
观察者模式定义了对象间的一对多依赖关系,让一个或多个观察者对象观察一个主题对象。当主题对象的状态发生变化时,系统能通知所有的依赖于此对象的观察者对象,从而使得观察者对象能够自动更新。
在观察者模式中,被观察的对象常常也被称为目标或主题(Subject),依赖的对象被称为观察者(Observer)。
Observer,观察者接口:
1 public interface Observer{ 2 void update(Observable o, Object arg); 3 }
Observable,目标或主题
1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.Iterator; 4 5 public abstract class Observable{ 6 ///用一个List来保存该对象上所有绑定的事件监听器 7 List<Observer> observers = new ArrayList<Observer>(); 8 9 ///定义一个方法,用于从该主题上注册观察者 10 public void registObserver(Observer o){ 11 observers.add(o); 12 } 13 14 ///定义一个方法,用于该主题中删除观察者 15 public void removeObserver(Observer o){ 16 observers.add(o); 17 } 18 19 ///通知该主题上注册的所有观察者 20 public void notifyObservers(Object value){ 21 ///遍历注册到该被观察者上的所有观察者 22 for(Iterator it = observers.iterator(); it.hasNext();){ 23 Observer o = (Observer)it.next(); 24 ///显示每个观察者的update方法 25 o.update(this, value); 26 } 27 } 28 }
Product被观察类:
1 public class Product extends Observable{ 2 ///定义两个属性 3 private String name; 4 private double price; 5 6 ///无参数的构造器 7 public Product(){ 8 } 9 10 public Product(String name, double price){ 11 this.name = name; 12 this.price = price; 13 } 14 15 public String getName(){ 16 return name; 17 } 18 19 ///当程序调用name的setter方法来修改Product的name属性时 20 ///程序自然触发该对象上注册的所有观察者 21 public void setName(String name){ 22 this.name = name; 23 notifyObservers(name); 24 } 25 26 public double getPrice(){ 27 return price; 28 } 29 30 ///当程序调用price的setter方法来修改Product的price属性时 31 ///程序自然触发该对象上注册的所有观察者 32 public void setPrice(double price){ 33 this.price = price; 34 notifyObservers(price); 35 } 36 }
NameObserver名称观察者:
1 import javax.swing.JFrame 2 import javax.swing.JLabel; 3 4 public class NameObserver implements Observer{ 5 ///实现观察者必须实现的update方法 6 public void update(Observable o, Object arg){ 7 if(arg instanceof String){ 8 ///产品名称改变值在name中 9 String name = (String)arg; 10 ///启动一个JFrame窗口来显示被观察对象的状态改变 11 JFrame f = new JFrame("观察者"); 12 JLabel l = new JLabel("名称改变为:" + name); 13 f.add(l); 14 f.pack(); 15 f.setVisible(true); 16 System.out.println("名称观察者:" + o + "物品名称已经改变为:" + name); 17 } 18 } 19 }
PriceObserver价格观察者:
1 public class PriceObserver implements Observer{ 2 ///实现观察者必须实现的update方法 3 public void update(Observable o, Object arg){ 4 if(arg instanceof Double){ 5 System.out.println("价格观察者:" + o + "物品价格已经改变为:" + arg); 6 } 7 } 8 }
测试:
1 public class Test{ 2 public static void main(String[] args){ 3 ///创建一个被观察者对象 4 Product p = new Product("电视机", 176); 5 ///创建两个观察者对象 6 NameObserver no = new NameObserver(); 7 PriceObserver po = new PriceObserver(); 8 ///向被观察对象上注册两个观察者对象 9 p.registObserver(no); 10 p.registObserver(po); 11 ///程序调用setter方法来改变Product的name和price属性 12 p.setName("书桌"); 13 p.setPrice(345f); 14 } 15 }
其中Java工具类提供了被观察者抽象基类:java.util.Observable。观察者接口:java.util.Observer。
我们可以把观察者接口理解成事件监听接口,而被观察者对象也可当成事件源处理——换个角度来思考:监听,观察,这两个词语之间有本质的区别吗?Java事件机制的底层实现,本身就是通过观察者模式来实现的。除此之外,主题/订阅模式下的JMS本身就是观察者模式的应用。
转自:http://www.rosoo.net/a/201210/16337.html

浙公网安备 33010602011771号