既是大俠,本事固然了得。還記得拔一撮猴毛,吹出萬千小猴子,這就是咱們第一位大俠(原型模式)的本事。另外一位,雖有真假猴王讓人分辨不清,當真的永遠都是真的,這就是單例模式。html
1.複製一個(不是新建)已經存在的實例(繼承Clone)來返回新的實例;函數
2.多用於建立複製或者耗時的實例,此時比從頭建立更高效。spa
1: public class Prototype implements Cloneable {
2: ...
3: ...
4: public Object clone(){
5: try {
6: return super.clone();
7: } catch (Exception e) {
8: e.printStackTrace();
9: return null;
10: }
11: }
12: }
1: public static void main(String[] args) {
2: Prototype prototype=new ConcretePrototype("prototype");
3: Prototype prototype2=(Prototype)prototype.clone();
4: System.out.println(prototype.getName());
5: System.out.println(prototype2.getName());
6:
7: // prototype
8: // prototype
9: }
保證一個類僅有一個實例,並提供一個訪問他的全局變量prototype
1: public class Singleton {
2: /**
3: * 靜態的自身變量
4: */
5: private static Singleton singleton;
6:
7: /**
8: * 構造函數私有化,防止外界直接建立
9: */
10: private Singleton(){
11:
12: }
13:
14: public static Singleton getSingleton(){
15: if (singleton==null) {
16: singleton=new Singleton();
17: }
18: return singleton;
19: }
20: }
1: public static void main(String[] args) {
2: Singleton singleton=Singleton.getSingleton();
3: Singleton singleton2=Singleton.getSingleton();
4:
5: System.out.println(singleton);
6: System.out.println(singleton2);
7: // Singleton.Singleton@9e5c73
8: // Singleton.Singleton@9e5c73
9: }