JAva設計モード_プロトタイプモード
2905 ワード
一、簡単な形式の原型モード
二、登録形式のプロトタイプ
package com.wangbiao.test_first;
/**
*
*
* @author WangBiao
*
*/
public abstract class CommonInterface {
public abstract CommonInterface clone();
}
//
class Class_first extends CommonInterface{
@Override
public CommonInterface clone() {
Class_first c=new Class_first();
return c;
}
}
//
class Class_second extends CommonInterface{
@Override
public CommonInterface clone() {
Class_second c=new Class_second();
return c;
}
}
class Main_Test{
public static void main(String[] args) {
CommonInterface common=new Class_second();
CommonInterface common_clone=common.clone();
}
}
二、登録形式のプロトタイプ
package com.wangbiao.test_second;
import java.util.HashMap;
/**
*
*
*
* @author WangBiao
*
*/
public abstract class CommonInterface {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract CommonInterface clone();
}
//
class Class_first extends CommonInterface {
@Override
public CommonInterface clone() {
Class_first c = new Class_first();
c.setName(this.getName());
return c;
}
}
//
class Class_second extends CommonInterface {
@Override
public CommonInterface clone() {
Class_second c = new Class_second();
c.setName(this.getName());
return c;
}
}
class ProtoTypeManagement {
private static HashMap<String, CommonInterface> map = new HashMap<String, CommonInterface>();
private ProtoTypeManagement() {
}
public synchronized static void addProtoType(String name, CommonInterface c) {
map.put(name, c);
}
public synchronized static void removeProtoType(String name) {
map.remove(name);
}
public synchronized static CommonInterface getProtoType(String name) throws Exception {
if (!map.containsKey(name)) {
//
System.out.println(" ");
throw new Exception(" ");
}
CommonInterface portoType = map.get(name);
return portoType;
}
}
class Main_Test {
public static void main(String[] args) throws Exception {
CommonInterface common = new Class_second();
common.setName("test");
System.out.println(common.getName());
ProtoTypeManagement.addProtoType("P1", common);
CommonInterface common_clone_first = ProtoTypeManagement.getProtoType("P1").clone();
System.out.println(common_clone_first.getName());
//
CommonInterface temp = new Class_second();
temp.setName("test_again");
ProtoTypeManagement.addProtoType("P1", temp);
CommonInterface common_clone_second=ProtoTypeManagement.getProtoType("P1").clone();
System.out.println(common_clone_second.getName());
//
ProtoTypeManagement.removeProtoType("P1");
CommonInterface common_clone_third=ProtoTypeManagement.getProtoType("P1").clone();
}
}