今天去打钥匙,在等待打钥匙的过程中,突然想到了设计模式中的原型(Prototype)模式。师傅打钥匙的过程大概是这样的,师傅拿出一把钥匙,这把钥匙暂时是什么锁都不能开的,然后我告诉师傅要按着我的要求复制一把,然后师傅就按着我这把钥匙的要求复制出了。来看看
下面我们用代码来看看,钥匙原型
package com.tankiy.Prototype;
import java.util.Properties;
/**
* <p>Title: 原型模式(Prototype)</p>
*
* <p>Description: </p>
*
* @author Tankiy
* @version 1.0
*/
public abstract class Prototype implements Cloneable {
private String name;
public Prototype(String name) {
this.name = name;
}
public abstract Prototype Clone();
public abstract void Display();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.tankiy.Prototype;
/**
* <p>Title: 原型模式(Prototype)</p>
*
* <p>Description: </p>
*
* @author Tankiy
* @version 1.0
*/
public class Key extends Prototype {
public Key(String name) {
super(name);
}
public Prototype Clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public void Display() {
System.err.println("类型:" + getName());
}
}
package com.tankiy.Prototype;
/**
* <p>Title: 原型模式(Prototype)</p>
*
* <p>Description: </p>
*
* @author Tankiy
* @version 1.0
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Prototype key1 = new Key("钥匙1");
key1.Display();
Prototype key2 = key1.Clone();
key2.setName("钥匙2");
key2.Display();
}
}
再看下UML类图
来试试吧。