設計模式(Design Pattern) - 創建型模式(Creational Pattern) - 原型模式(Prototype)
用原型實例指定創建對象的種類,並且通過複製這些原型,創建新的對象。
1、簡單原型
1.1、說明:
(1)Prototype 產品抽象原型.接口;
(2)PrototypeA 原型.實現類;
(3)PrototypeB 原型.實現類。
1.2、Java實現,代碼如下:
(1)Prototype
package com.java.designPattern.prototype.simplePrototype;
/**
* 抽象原型(接口)
*
*/
public abstract class Prototype implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() {
Object object = null;
try {
object = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return object;
}
}
(2)PrototypeA
package com.java.designPattern.prototype.simplePrototype;
/**
* 具體原型.實現類
*
*/
public class PrototypeA extends Prototype {
public PrototypeA() {
setName("prototpye A");
}
}
(3)PrototypeB
package com.java.designPattern.prototype.simplePrototype;
/**
* 具體原型.實現類
*
*/
public class PrototypeB extends Prototype {
public PrototypeB() {
setName("prototpye B");
}
}
(4)Test
package com.java.designPattern.prototype.simplePrototype;
/**
* 測試類
*
*/
public class Test {
public static void main(String[] args) {
Prototype prototypeA = new PrototypeA();
System.out.println(prototypeA.getName());
Prototype prototypeB = new PrototypeB();
System.out.println(prototypeB.getName());
}
}
輸出:
prototpye A
prototpye B
2、有管理器的原型
2.1、說明:
(1)Prototype 產品抽象原型.接口;(同1)
(2)PrototypeA 原型.實現類;(同1)
(3)PrototypeB 原型.實現類;(同1)
(4)PrototypeManager 原型管理器。
2.2、Java實現,代碼如下:
(1)Prototype
(2)PrototypeA
(3)PrototypeB
(4)PrototypeManager
package com.java.designPattern.prototype.prototypeManager;
import java.util.HashMap;
import java.util.Map;
/**
* 原型管理器
*
*/
public class PrototypeManager {
private static Map<String, Prototype> map = new HashMap<String, Prototype>();
private PrototypeManager() {
}
public synchronized static void setPrototype(String id, Prototype prototype) {
map.put(id, prototype);
}
public synchronized static Prototype getPrototype(String id) {
return map.get(id);
}
public synchronized static void removePrototype(String id) {
map.remove(id);
}
}
(5)Test
package com.java.designPattern.prototype.prototypeManager;
/**
* 測試類
*
*/
public class Test {
public static void main(String[] args) {
Prototype prototypeA = new PrototypeA();
Prototype prototypeB = new PrototypeB();
PrototypeManager.setPrototype("a", prototypeA);
PrototypeManager.setPrototype("b", prototypeB);
System.out.println(PrototypeManager.getPrototype("a").getName());
System.out.println(PrototypeManager.getPrototype("b").getName());
}
}
輸出:
prototpye A
prototpye B