006、原型模式

一、UML图

二、实例

1、Prototype

package com.designPattern.prototype;

/**
 * Created by ZhangJintao on 2020/3/10.
 */
public abstract class HealthStatus implements Cloneable {
    // 体温是否大于37.3度
    private boolean bodyTemperatureBigThanNormal;

    // 咳嗽
    private boolean cough;

    // 体感虚弱
    private boolean weak;

    public boolean isBodyTemperatureBigThanNormal() {
        return bodyTemperatureBigThanNormal;
    }

    public void setBodyTemperatureBigThanNormal(boolean bodyTemperatureBigThanNormal) {
        this.bodyTemperatureBigThanNormal = bodyTemperatureBigThanNormal;
    }

    public boolean isCough() {
        return cough;
    }

    public void setCough(boolean cough) {
        this.cough = cough;
    }

    public boolean isWeak() {
        return weak;
    }

    public void setWeak(boolean weak) {
        this.weak = weak;
    }

    @Override
    protected HealthStatus clone() throws CloneNotSupportedException {
        return (HealthStatus) super.clone();
    }

    protected void showHealth(){
        System.out.println("bodyTemperatureBigThanNormal=" + bodyTemperatureBigThanNormal + "   cough=" + cough + "    weak=" + weak);
    }
}

2、ConcretePrototype

package com.designPattern.prototype;

/**
 * Created by ZhangJintao on 2020/3/10.
 */
public class HealthStatusOk extends HealthStatus{
    public HealthStatusOk() {
        this.setBodyTemperatureBigThanNormal(false);
        this.setCough(false);
        this.setWeak(false);
    }
}

3、main(Client)

package com.designPattern.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZhangJintao on 2020/3/10.
 */
public class main {
    public static void main(String[] args) {
        List<HealthStatus> healthStatusList = new ArrayList<HealthStatus>();

        try {
            HealthStatusOk healthStatusOk = new HealthStatusOk();

            for (int i = 0 ; i < 10 ; i++){
                HealthStatus healthStatus = healthStatusOk.clone();

                if (i % 3 == 0){
                    healthStatus.setCough(true);
                }

                healthStatusList.add(healthStatus);
            }

        }catch (CloneNotSupportedException exception) {
            exception.printStackTrace();
        }


        for (HealthStatus healthStatus : healthStatusList ) {
            healthStatus.showHealth();
        }

    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值