单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
几种经典的实现方式
package com.ghods.lesson1.designpattern.singleton;
/**
* 线程安全的 懒汉模式
*/
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
/**
* 饿汉模式
*/
class Singleton2 {
private Singleton2() {
}
private static Singleton2 instance = new Singleton2();
public static Singleton2 getInstance() {
return instance;
}
}
/**
* 双重校验锁 的懒汉模式
*/
class Singleton3 {
private Singleton3() {
}
private static Singleton3 singleton = null;
public static Singleton3 getInstance() {
if (singleton == null) {
synchronized (Singleton3.class) {
if (singleton == null) {
singleton = new Singleton3();
}
}
}
return singleton;
}
}
推荐blog文章:http://www.blogjava.net/kenzhh/archive/2013/07/05/357824.html
Prototype(原型模式):用原型实例指定创建对象的种类,并且通过拷贝这个原型来创建新的对象。
package com.ghods.lesson1.designpattern.prototype;
/**
* 抽象原型角色
*/
public abstract class Prototype implements Cloneable {
private A a;
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
/**
* 克隆自身方法
*
* @return
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class A {
public A(){}
public A(String str) {
this.str = str;
}
private String str = "默认值";
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
package com.ghods.lesson1.designpattern.prototype;
/**
* 具体原型实现
*/
public class ConcretePrototype extends Prototype{
public static void main(String [] args) throws CloneNotSupportedException{
Prototype prototype = new ConcretePrototype();
prototype.setA(new A("原型的值"));
ConcretePrototype concretePrototype1 = (ConcretePrototype) prototype.clone();
//将会输出‘原型的值’,而不是‘默认值’;因此这是浅复制
System.out.println(concretePrototype1.getA().getStr());
}
}
如果需要深度复制,当然需要重写Prototype的clone方法了。
public Object clone() throws CloneNotSupportedException {
this.a = new A();
return super.clone();
}
其它设计模式可以参见《Design Patterns: Elements of Reusable Object-Oriented Software》(即后述《设计模式》一书),由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 合著(Addison-Wesley,1995)。这几位作者常被称为"四人组(Gang of Four)",而这本书也就被称为"四人组(或 GoF)"书。