|
JAVA的设计模式经前人总结可以分为23种,希望在学习完毕后能对自己的工作有所帮助。
设计模式根据使用类型可以分为三种:
1、 创建模式:工厂模式、单子模式、建造者模式、原型模式、工厂方法模式。 2、 结构模式:外观模式、代理模式、适配器模式、组合模式、装饰模式、桥模式、 共享模式。 3、 行为模式:模板模式、纪念品模式、观察者模式、责任链模式、命令模式、声明模式、 策略模式、中介模式、解释器模式、访问模式。
注:以上翻译不准确,还是以英文为准。
一、 创建模式: 1、 工厂模式(Factory),工厂方法模式(略): 工厂模式是我们最常用的模式了,著名的Jive论坛 ,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见。
工厂模式有好多种其中最常用的是简单的工厂模式,例如下
public class Factory{ public static windows creator(int which){ //getClass 产生Sample 一般可使用动态类装载装入类。 if (which==1) return new windows1 (); else if (which==2) return new windows2(); } Public static void main(String []args){ Windows = Factory.creator(1); Windows.fun(); } } Public Interface windows{ Public abstract void fun(); } Public class windows1 implements windows{ Public void fun(){ System.out.println(“hello am 1”); } } Public class windows2 implements windows(){ Public void fun(){ System.out.println(“hello am 2”); } } 步骤: 1、 建立两个子类的公共接口方法。 2、 两个子类实现接口的方法。 3、 建立公共工厂类提供公共方法返回接口类型,参数是区别两个子类的依据。 4、 调用接口提供的公共方法,系统自动调用子类的方法。
2、 单子模式(Singleton): Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。 例子一: import java.util.*; class Singleton{ private static Singleton instance; private Vector v; private boolean inUse;
private Singleton(){ v = new Vector(); v.addElement(new Object()); inUse = true; }
public static Singleton getInstance(){ if (instance == null) //1 instance = new Singleton(); //2 return instance; //3 } } 例子二: public class SingletonSmple { private static SingletonSmple singleton = null; static { singleton = new SingletonSmple(); } public static synchronized SingletonSmple getInstence() throws SingletonException { if(singleton == null){ singleton = new SingletonSmple(); } return singleton ; } } class hello{ public static void main(String[]args){ for(int i =0 ; i< 2 ; i++){ try { System.out.println(SingletonSmple.getInstence()); } catch (Exception ex) { } } } }
|