数据双向同步之观察者模式

数据双向同步之观察者模式

当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。

这系列博客主要是为了总结项目中所用到了一些设计模式,为方便说明对其进行了简化。

在此,我将一个虚拟对象VDevice当做是Subject,具体虚拟空调对象VAircon实现该接口;

具体的底层设备对象UDevice当做是Observer,具体的底层空调对象Gree和Panosonic继承Observer

/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public interface VDevice {
    void notifyAllUDevice();
    void attach(UDevice uDevice);
    void setAttribute(Double attribute);
    Double getAttribute();
    void IncreaseAttribute();
}
import java.util.ArrayList;
import java.util.List;

/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public class VAircon implements VDevice{
    private List<UDevice> uDevices = new ArrayList<>();
    //虚拟对象属性
    Double Attribute;

    //getter setter...
    @Override
    public void setAttribute(Double attribute) {
        this.Attribute = attribute;
    }
    @Override
    public Double getAttribute() {
        return Attribute;
    }

    //关键方法,升高虚拟设备某属性值并通相关设备
    @Override
    public void IncreaseAttribute() {
        Attribute += 1.0;
        notifyAllUDevice();
    }

    //添加相关设备
    @Override
    public void attach(UDevice uDevice) {
        uDevices.add(uDevice);
    }

    //通知
    @Override
    public void notifyAllUDevice() {
        for (UDevice uDevice : uDevices) {
            uDevice.update(Attribute);
        }
    }
}
/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public abstract class UDevice {
    protected VDecice vDecice;
    public abstract void update(Double attribute);


}

/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public class Gree extends UDevice {
    Double temperature;

    public Gree(VDevice vAircon, Double temperature) {
        this.temperature = temperature;
        this.vAircon = vAircon;
        this.vAircon.attach(this);
    }

    @Override
    public void update(Double attribute) {
        warm(attribute);
    }
    //设备自己的升温api
    private void warm(Double attribute) {
        this.temperature = attribute;
        System.out.println(this.temperature);
    }

}
/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public class Panasonic extends UDevice {
    Double temperature;

    public Panasonic(VDevice vAircon, Double temperature) {
        this.temperature = temperature;
        this.vAircon = vAircon;
        this.vAircon.attach(this);
    }

    @Override
    public void update(Double attribute) {
        up(attribute);
    }
    //设备自己的升温api
    private void up(Double attribute) {
        this.temperature = attribute;
        System.out.println(this.temperature);
    }


}


/**
 * Author:cafe3165
 * Date:2020-05-03
 */
public class DeviceDemo {
    public static void main(String[] args) {
        VDevice vAircon = new VAircon();
        vAircon.setAttribute(20.0);
        UDevice gree = new Gree(vAircon, 10.0);
        UDevice panasonic = new Panasonic(vAircon, 25.0);
        vAircon.IncreaseAttribute();

    }
}

posted @ 2020-05-03 10:22  爱拖交作业的小明  阅读(454)  评论(0编辑  收藏  举报