Gof设计模式的UML 类别图:
(1) Simple factory模式:
(2) Abstract factory模式:
(3) Builder模式:
注:您想要建立一个迷宫产生程式,迷宫使用二维阵列来定义,0表示道路,1表示墙,2表示宝物,根据所定义的二维迷宫阵列,您想要程式自动产生各种不同材质的迷宫,例如砖墙迷宫,钻石迷宫等等。
(4) Factory Method模式:
文件编辑器
(5) Prototype模式:
您从图书馆的期刊从发现了几篇您感兴趣的文章,由于这是图书馆的书,您不可以直接在书中作记号或写字,所以您将当中您所感兴趣的几个主题影印出来,这下子您就可在影印的文章上画记重点。
Prototype模式的作用有些类似上面的描述,您在父类别中定义一个clone()方法,而在子类别中重新定义它,当客户端对于所产生的物件有兴趣并想加以利用,而您又不想破坏原来的物件,您可以产生一个物件的复本给它。
Prototype具有展示的意味,就像是展览会上的原型车款,当您对某个车款感兴趣时,您可以购买相同款示的车,而不是车展上的车。
Java中的clone()方法是继承自Object
(6) Singleton单例模式:
monUtil的Singleton模式:
private monUtil = null;
public monUtil getInstance(){
//加同步锁,防止多线程情况下同时进入申请实例
monUtilLock){
monUtil == null){
//创建工具类的单实例
commonUtil = monUtil();
}
//返回实例
monUtil;
}
}
public class Singleton {//单线程的情况下单例模式
private static Singleton instance = null;
private Singleton() {
// ....
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public class Singleton {//多线程的情况下单例模式加互斥锁
private static Singleton instance = null;
private Singleton(){}
synchronized static public Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Double-check Locking的模式:
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null){
synchronized(){
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Reflection机制实现单例模式:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// ....
}
public static Singleton getInstance() {
if (instance == null) {
// getEnv表示环境变数
String style = getEnv("style");
try {
instance = (Singleton)
(style).newInstance();
}
catch(Exception e) {
("Sorry! No such class defined!");
}
}
return instance;
}
// ....
}
Registry of Singleton方法:
import .*;
p
HeadFirst设计模式流程图个人总结 来自淘豆网m.daumloan.com转载请标明出处.