设计模式----Prototype(原形)模式
来源:互联网 发布:vwap算法 编辑:程序博客网 时间:2024/05/01 06:18
设计模式----Prototype(原形)模式
GoF:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
用过Java集合比如说,ArrayList、HashMap等的人都肯定有过将一个对象copy给另一个对象的经历,其中clone ()方法可能都用过。Prototype模式就起到这样的作用。Prototype模式允许一个对象再创建另一个对象,而根本无需知道任何如何创建的细节。(该处摘自板桥里人-设计模式之Prototype(原型))这里我们不讨论深拷贝和浅拷贝的问题。(相关知识请参考《Thing in Java》附录A那里有详细的解释)
在Java中由于类Object提供了clone ()方法,来实现对象的克隆。所以在Java中Prototype模式的实现变得非常简单。
Prototype模式,其实也是非常简单的模式之一。我们通过一个实例来展现Prototype模式:
package Prototype;
public abstract class AbstractMobile implements Cloneable
{
String mobileName;
public void setMobileName(String name)
{
mobileName = name;
}//end setMobileName(...)
public String getMobileName()
{
return mobileName;
}//end getMobileName()
public Object clone()//实现clone方法
{
Object object = null;
try{
object = super.clone();
}catch(CloneNotSupportedException cloneException){
System.err.println("AbstratMobile is not Cloneable");
cloneException.printStackTrace();
}
return object;
}//end clone()
}//end abstract class AbstractMobile
package Prototype;
public class
{
/** Creates a new instance of
public
{
// super.setMobileName("NOKIA");
}//end
}//end class
Prototype模式的调用:
/*
* PrototypePattern.java
*
* Created on
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package Prototype;
public class PrototypePattern
{
AbstractMobile mobile = new
AbstractMobile newMobile = (Mobile)mobile.clone();//返回的是Object这里需要类型转换
public void showPrototypePattern()
{
mobile.setMobileName("NOKIA");
String mobileType = mobile.getMobileName();
System.out.println("The new mobile is " + mobileType);
}//end showPrototypePattern()
public static void main(String[] args)
{
System.out.println("The Prototype Pattern!");
PrototypePattern pp = new PrototypePattern();
pp.showPrototypePattern();
}//end main(...)
}//class PrototypePattern
下面是UML图,这里的图比较简单。但是已经能够反映出Prototype模式了。
在Java中Prototype模式几乎变成了clone ()方法的调用。其实Java先天复杂的类库给设计模式的实现提供了便利条件。比如Observer模式,Interator模式等。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=968297
- 设计模式----Prototype(原形)模式
- 设计模式--创建型-Prototype(原形)
- 大话设计模式 原形模型
- 设计模式——原形模式
- 设计模式:Prototype模式
- 设计模式-Prototype模式
- 设计模式-Prototype模式
- 设计模式 - Prototype 模式
- 设计模式-Prototype模式
- 设计模式--Prototype模式
- 实现Prototype设计模式
- 实现Prototype设计模式
- 设计模式之Prototype
- 设计模式之Prototype
- Prototype设计模式
- 设计模式之Prototype
- 设计模式之Prototype
- 实现Prototype设计模式
- 《设计模式精解》学习笔记(十五)------FactoryMethod(工厂方法)模式
- 做树题目心得体会
- 《设计模式精解》学习笔记(十六)------总结
- Jabber学习笔记 之二
- 设计模式----Builder(生成器)模式
- 设计模式----Prototype(原形)模式
- 程序员考试笔记
- 设计模式----Composite(组合)模式
- 耳朵发热
- 设计模式----Flyweight(享元)模式
- 设计模式----Proxy(代理)模式
- 数据结构笔记
- .net精简框架集(WinCE平台下),XML反序列化成功与否与时间相关
- 设计模式----Chain of Responsibility(职责链)模式