设计模式之观察者模式

其实大多数设计模式里面都有多态的体现,观察这模式其实 就是人与人之间一样,观察一个人状态的变化,然后做出相应的处理。

package com.lyc.design;

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

public class Observer {
public static void main(String[] args) {
Subject subject = new Subject();

new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);

System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}

class Subject {

private List<Observer1> observers = new ArrayList<Observer1>();
private int state;

public int getState() {
return state;
}

public void setState(int state) {
this.state = state;
//改变后调用相应的方法
notifyAllObservers();
}

public void attach(Observer1 observer) {
observers.add(observer);
}

public void notifyAllObservers() {
for (Observer1 observer : observers) {
observer.update();
}
}
}

abstract class Observer1 {
protected Subject subject;

public abstract void update();
}

class BinaryObserver extends Observer1 {

public BinaryObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}

@Override
public void update() {
System.out.println("Binary String: " + Integer.toBinaryString(subject.getState()));
}
}

class OctalObserver extends Observer1 {

public OctalObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}

@Override
public void update() {
System.out.println("Octal String: " + Integer.toOctalString(subject.getState()));
}
}

class HexaObserver extends Observer1 {

public HexaObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}

@Override
public void update() {
System.out.println("Hex String: " + Integer.toHexString(subject.getState()).toUpperCase());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值