用专业的话来说,是这样的:观察者模式定义对象间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。
用我自己的话说是这样的:法外狂徒张三欠了一屁股债,追债人不知道张三什么时候有钱还。但是张三是个很守信用的人,他一有了钱就会去通知追债人去还债。
即张三状态发生变化,相关的依赖对象(追债人)皆会被通知,并且更新~
上代码:
/** * @Author:Nyapii */ public class ObserverPattern { public static void main(String[] args) { Debit zhangSan = new ZhangSan(); zhangSan.borrow(new Wangwu()); zhangSan.borrow(new Lisi()); zhangSan.notifyCredits(); } } interface Debit{ void borrow(Credit credit); void notifyCredits(); } class ZhangSan implements Debit{ private List<Credit> allCredits = new ArrayList<>(); private Integer state = 0; // 0表示没钱,1表示有钱 @Override public void borrow(Credit credit) { allCredits.add(credit); } @Override public void notifyCredits() { allCredits.forEach(credit -> credit.takeMoney()); } } interface Credit{ void takeMoney(); } class Lisi implements Credit{ @Override public void takeMoney() { System.out.println("李四要钱!"); } } class Wangwu implements Credit{ @Override public void takeMoney() { System.out.println("王五要钱!"); } }
/** * @Author:Nyapii */ public class ObserverPattern { public static void main(String[] args) { Debit zhangSan = new ZhangSan(); zhangSan.borrow(new Wangwu()); zhangSan.borrow(new Lisi()); zhangSan.notifyCredits(); } } interface Debit{ void borrow(Credit credit); void notifyCredits(); } class ZhangSan implements Debit{ private List<Credit> allCredits = new ArrayList<>(); private Integer state = 0; // 0表示没钱,1表示有钱 @Override public void borrow(Credit credit) { allCredits.add(credit); } @Override public void notifyCredits() { allCredits.forEach(credit -> credit.takeMoney()); } } interface Credit{ void takeMoney(); } class Lisi implements Credit{ @Override public void takeMoney() { System.out.println("李四要钱!"); } } class Wangwu implements Credit{ @Override public void takeMoney() { System.out.println("王五要钱!"); } }
运行结果:
标签:credit,void,观察者,模式,Credit,Override,new,public From: https://www.cnblogs.com/Nyapii/p/17306920.html