建造模式-原始模型模式

原始模型模式:通过给出一个原型对象 来指明所要创建的对象的类型,然后用复制这个模型对象的办法创建出更多同类型的对象。

原始模型模式分为两种:简单形式,登记形式

先看简单形式

客户角色

package com.javapatterns.prototype;

public class Client
{
    public void operation(Prototype example)
    {
    	prototype = (Prototype) example.clone();
    }
    
    private Prototype prototype;
}

 抽象原型

package com.javapatterns.prototype;

public interface Prototype extends Cloneable
{
    Object clone();
}

 

具体原型

package com.javapatterns.prototype;

public class ConcretePrototype implements Prototype
{
    public Object clone()
    {
        try
        {
	        return super.clone();
        }
        catch(CloneNotSupportedException e)
        {
            //write your code here
            return null;
        }
    }
}

 

 

 

登记式

 客户端

package com.javapatterns.prototype;

public class Client {
	private PrototypeManager mgr;
	private Prototype prototype;

	public void registerPrototype() {
		prototype = new ConcretePrototype();
		Prototype copytype = (Prototype) prototype.clone();
		mgr.add(copytype);
	}
}

  抽象原型

package com.javapatterns.prototype;

public interface Prototype extends Cloneable
{
    Object clone();
}

 

具体原型

package com.javapatterns.prototype;

public class ConcretePrototype implements Prototype
{
	public synchronized Object clone(){
		Protype temp = null;
		try
		{
			temp = (Prototype) super.clone();

			return temp;
		}
		catch(CloneNotSupportedException e)
		{
			System.out.println("Clone failed.");
		}
		finally
		{
			return temp;
		}
	}
    }

 原型管理器

package com.javapatterns.prototype.manager;

import java.util.Vector;

public class PrototypeManager
{
    public void add(Prototype object)
    {
        objects.add(object);
    }

    public Prototype get(int i)
    {
        return (Prototype) objects.get(i);
    }

    public int getSize()
    {
        return objects.size();
    }

    private Vector objects = new Vector();
}

 

你可能感兴趣的:(prototype)