设计模式7---原型模式

  原型模式属于对象的创建模式。通过给出一个原型对象来指明所有创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象。这就是选型模式的用意。

  

 Client端只需要知道接口的clone方法,而不需要具体哪些东西被clone了。

ConCreatePrototype实际上对于Client端来说是透明的。

 

public interface IProductor {
    public Object clone();
    void setId(int id);
    String display();
}
public class Ball implements IProductor {
    
    private int id = -1;
    private String name;
    private double price;
    private String function;
        
    public Ball(String name, double price, String function) {
        this.name = name;
        this.price = price;
        this.function = function;
    }

    @Override
    public void setId(int id) {
        // TODO Auto-generated method stub
        this.id = id;
    }

    @Override
    public String display() {
        // TODO Auto-generated method stub
        String result = (name+"\t"+function+"\t"+price+"\t"+id);
        System.out.println(result);
        return result;
    }

    @Override
    public IProductor clone(){
        IProductor _mproductor = new Ball(this.name,price,function);
        return _mproductor;
    }
    
    
    
}
package com.jayfulmath.designpattern.prototype;

import com.jayfulmath.designpattern.main.BasicExample;

public class PrototypeMain extends BasicExample {

    @Override
    public void startDemo() {
        // TODO Auto-generated method stub
        Ball _mBall = new Ball("football",109.8,"play football");
        _mBall.setId(1);
        
        Ball _mBallA = (Ball) _mBall.clone();
        _mBallA.setId(2);
        
        _mBall.display();
        _mBallA.display();
    }

}

原型模式就是,我们生产一个ball有很多属性,但是对于同样一个球,只有id不同,所以我们只需要通过clone的方式快速复制这些对象。

posted on 2014-11-30 15:42  Joyfulmath  阅读(147)  评论(0编辑  收藏  举报

导航