利用开闭原则重构原有的Alert类代码

UML类图

在这里插入图片描述

代码

import java.util.*;

//接口
interface state_interface{
	public void check();
	public void updateValue(float v);
	public void setThreshold(float threshold);
}

//基类
abstract class state implements state_interface{

	public Threshold thre;
	public float value;

	state(float threshold)
	{
		thre=new Threshold(threshold);
	}

	@Override
	public void setThreshold(float v)
	{
		thre.SetThreshold(v);
	}

	public void updateValue(float v) {
		value=v;
	}

	abstract public void check();//子类实现这个

}

//阈值类
class Threshold
{
	private float max;


	public Threshold(float max)
	{
		this.max = max;
	}

	public void SetThreshold(float max)
	{
		this.max = max;
	}

	public float Max()
	{
		return this.max;
	}

}

//温度类,继承基类
class Temperature extends state
{
	Temperature(float v)
	{
		super(v);
	}

	@Override
	public void check() {
		if(super.value > super.thre.Max())
			System.out.println("temperature is out of range!");
	}
}

//PH类,继承基类
class ph_value extends state
{
	ph_value(float v)
	{
		super(v);
	}

	@Override
	public void check() {
		if(super.value > super.thre.Max())
			System.out.println("PH is out of range!");
	}

}

//压强类,继承基类
class pressure extends state
{
	pressure(float v)
	{
		super(v);
	}

	@Override
	public void check() {
		if(super.value > super.thre.Max())
			System.out.println("pressure is out of range!");
	}

}

//警报类
public class Alert
{
	private ArrayList<state> stateArray;//存放状态的容器

	public Alert()
	{
		stateArray = new ArrayList<state>();
	}
	
	//添加状态
	public void Add(state s)
	{
		stateArray.add(s);
	}

	public void Check()
	{
		for(state s:stateArray)//挨个检查,多态
		{
			s.check();
		}
	}
}

运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值