[3] [对象创建] ( 3 ) 原型模式 prototype
总结
-
定义
在软件系统中,
有时候需要多次创建某一类型的对象,
为了简化创建过程,
可以只创建一个对象,
然后再通过克隆的方式复制出多个相同的对象,
这就是原型模式的设计思想.
-
干什么用的?
主要解决对象复制的问题,
它的核心就是 Clone() 方法,
返回原型对象的复制品。
-
和工厂模式的相似点?
和工厂模式一样解决new的耦合问题,
用于隔离对象的使用者和具体类型(易变类)之间的耦合关系,
它同样要求"易变类"拥有稳定的接口.
-
什么时候用原型模式? 和工厂模式的区别?
但是有时用工厂方法去创建一个带复杂结构复杂状态的对象实例并不方便,
此时可以用原型模式的克隆方法, 利用已有实例进行创建.
.
反过来说, 如果你用工厂模式很容易, 直接用工厂模式就行了.
java例子
package v13_prototype.java;
import java.util.Hashtable;
// 网球拍(抽象)
abstract class RacketPrototype {
protected String brand; // 品牌
protected String model; // 模型
protected double weight; // 重量
protected double balancePoint; // 重心
public RacketPrototype(String brand, String model, double weight, double balancePoint) {
this.brand = brand;
this.model = model;
this.weight = weight;
this.balancePoint = balancePoint;
}
public abstract RacketPrototype clone();
}
// 威尔逊网球拍
class WilsonTennisRacket extends RacketPrototype {
public WilsonTennisRacket(String brand, String model, double weight, double balancePoint) {
super(brand, model, weight, balancePoint);
}
// 克隆出新球拍
@Override
public RacketPrototype clone() {
System.out.printf("Wilson clone: %s %s %s %s\n", this.brand, this.model, this.weight, this.balancePoint);
return new WilsonTennisRacket(this.brand, this.model, this.weight, this.balancePoint);
}
}
// 海德网球拍
class HeadTennisRacket extends RacketPrototype {
public HeadTennisRacket(String brand, String model, double weight, double balancePoint) {
super(brand, model, weight, balancePoint);
}
// 克隆出新球拍
@Override
public RacketPrototype clone() {
System.out.printf("Head clone: %s %s %s %s\n", this.brand, this.model, this.weight, this.balancePoint);
return new WilsonTennisRacket(this.brand, this.model, this.weight, this.balancePoint);
}
}
// 网球拍管理器
class TennisRacketPrototypeManager {
private static Hashtable<String, RacketPrototype> racketMap = new Hashtable<String, RacketPrototype>();
public static RacketPrototype getClonedRacket(String model) {
RacketPrototype r = racketMap.get(model);
return (RacketPrototype) r.clone();
}
public static void buildProtypes() {
// 创建一个威尔逊球拍, 产品代号为"Pro Staff V14"
WilsonTennisRacket r1 = new WilsonTennisRacket("Wilson", "Pro Staff", 320.0, 32.5);
racketMap.put("pro staff", r1);
// 创建一个海德球拍, 产品代号为"GRAPHENE 360 EXTREME"
HeadTennisRacket h1 = new HeadTennisRacket("Head", "Graphene 360 Speed", 320.0, 32.5);
racketMap.put("graphene 360" , h1);
}
}
public class TennisPlayer {
public static void main(String[] args) {
// 创建2个球拍品牌
TennisRacketPrototypeManager.buildProtypes();
// 找到威尔逊球拍, 用这个威尔逊球拍,复制出十个一模一样的新球拍
for (int i = 0; i < 10; i++) {
TennisRacketPrototypeManager.getClonedRacket("pro staff");
}
}
}



浙公网安备 33010602011771号