Java设计模式---Prototype模式

具体的实现代码的demo:

样例为克隆一只羊:

public class Sheep implements Cloneable{
    private String name;
    private int age;
    private String color;

    @Override
    protected Object clone() {
        Sheep sheep =null;
        try {
            sheep = (Sheep)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return sheep;
    }

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}

测试代码:

/**
 * 原型模式的好处:当对象sheep 的属性值有变化的时候,无需动原来的代码
 */
public class SheepTest {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("tom",3,"white");
        Object sheep1 = (Sheep)sheep.clone();
        Object sheep2 = (Sheep)sheep.clone();
        System.out.println(sheep1);
        System.out.println(sheep2);
    }
}

输出结果:

Sheep{name='tom', age=3, color='white'}
Sheep{name='tom', age=3, color='white'}

Spring源码中运用到该模式的地方,如下截图:

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值