Java设计模式之原型模式(Prototype)实践

       原型模式定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
       在运行期需要建立和删除原型,此时可以使用原型模式。

以下代码演示原型模式简单的实际运用:定义一个抽象类Ball:

package com.ldl.cn.PrototypeModel;

public abstract class Ball implements Cloneable{

    private String id;
    protected String name;
    
    abstract void say();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object clone(){
        Object cloneObj = null;
        try {
            cloneObj = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return cloneObj;
    }
}

分别定义类Baseball、Football继承Ball:

package com.ldl.cn.PrototypeModel;

public class Baseball extends Ball{

    public Baseball() {
        name = "Baseball";
    }
    
    @Override
    void say() {
        System.out.println("I'm a baseball.");
    }
}
package com.ldl.cn.PrototypeModel;

public class Football extends Ball{

    public Football() {
        name = "Football";
    }

    @Override
    void say() {
        System.out.println("I'm a football.");
    }
}

编写测试类:

package com.ldl.cn.PrototypeModel;

import java.util.Hashtable;

public class TestPrototypePattern {
    
    private static Hashtable<String, Ball> ballMap = new Hashtable<>();
    
    public static Ball getBall(String id){
        Ball ball = ballMap.get(id);
        return (Ball) ball.clone();
    }
    
    public static void main(String[] args) {
        Football football = new Football();
        football.setId("1");
        ballMap.put(football.getId(), football);
        
        Baseball baseball = new Baseball();
        baseball.setId("2");
        ballMap.put(baseball.getId(), baseball);
        
        Ball cloneBall1 = ballMap.get("1");
        System.out.println("Ball:"+cloneBall1.getName());
        
        Ball cloneBall2 = ballMap.get("2");
        System.out.println("Ball:"+cloneBall2.getName());
    }
}

运行结果:
Ball:Football
Ball:Baseball

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值