设计模式之原型模式
次访问
定义
维基百科上的一段定义:
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.
这段话的大意就是:原型模式就是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。这种设计模式主要用来避免:
1.像抽象工厂模式一样,将子类暴露给客户端。
2.避免创建新的对象所耗费的成本。
原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。
代码
package com.ans;
abstract class Resume implements Cloneable {
private String name;
private int Age;
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
}
class MyResume extends Resume {
public MyResume(String name, int age) {
setName(name);
setAge(age);
}
}
public class Prototype {
public static void main(String[] args) {
Resume resume = new MyResume("lixuehan",24);
Resume newResume = (Resume)resume.clone();
newResume.setName("leexuehan");
System.out.println(newResume.getName() + "," + newResume.getAge());
System.out.println(resume.getName() + "," + resume.getAge());
System.out.println(resume == newResume);
}
}
运行结果:
leexuehan,24
lixuehan,24
false
实现原型模式的关键就是拷贝类要实现Cloneable接口,然后实现 clone 方法。
从main函数的测试环节来看,Object 的默认的 clone 方法,实现的是深拷贝。因为最后在修改了名字之后,再打印原来的对象的名字的时候,依然没有变化。
附加:
这里复习下Java中抽象类和接口的区别:https://github.com/leexuehan/leexuehan.github.com/issues/98