观察者模式是一种行为模式,它定义了对象之间的一对多依赖关系,以便当一个对象更改状态时,它的所有依赖项都会收到通知并自动更新。
对象改变状态称为Subject,其依赖者称为Observers。
当您需要对象之间存在一对多依赖关系时,可以使用观察者模式,其中一个对象会更改其状态,并且许多依赖对象需要跟踪这些更改。
假设我们使用像X(Twitter)这样的SNS,公司和人们都有自己的帐户,人们可以关注他们最喜欢的公司,以便在公司发布有关新商品或促销商品时收到通知。在这种情况下,观察者模式就适用。


I公司界面:
public interface ICompany {
void registerAccount(IAccount account);
void removeAccount(IAccount account);
void notifyAccounts();
}
公司类别:
import java.util.ArrayList;
import java.util.List;
public class Company implements ICompany {
private List<IAccount> followers;
private String name;
private String saleItem;
public Company(String name) {
followers = new ArrayList<>();
this.name = name;
}
@Override
public void registerAccount(IAccount account) {
this.followers.add(account);
}
@Override
public void removeAccount(IAccount account) {
this.followers.remove(account);
}
@Override
public void notifyAccounts() {
for (IAccount follower : followers) {
follower.update(this);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSaleItem() {
return saleItem;
}
public void setSaleItem(String saleItem) {
this.saleItem = saleItem;
saleItemChanged();
}
public void saleItemChanged() {
notifyAccounts();
}
}
IAaccount接口:
public interface IAccount {
void update(Company company);
}
账户类别:
public class Account implements IAccount {
private String name;
public Account(String name) {
this.name = name;
}
@Override
public void update(Company company) {
System.out.println(this.name + " receives a new message from " + company.getName());
System.out.println("New sale item: " + company.getSaleItem());
}
}
客户端类:
public class Client {
public static void main(String[] args) {
Company apple = new Company("Apple"); // concrete subject
IAccount john = new Account("John");
IAccount david = new Account("David");
// John starts following Apple Inc.
apple.registerAccount(john);
apple.setSaleItem("iPhone 14");
System.out.println("**********************");
// David becomes a new follower to Apple Inc.
apple.registerAccount(david);
apple.setSaleItem("iPad");
System.out.println("**********************");
// John doesn't receive message from Apple Inc. as he deregistered for Apple Inc.
apple.removeAccount(john);
apple.setSaleItem("AirPods");
}
}
输出:
John receives a new message from Apple New sale item: iPhone 14 ********************** John receives a new message from Apple New sale item: iPad David receives a new message from Apple New sale item: iPad ********************** David receives a new message from Apple New sale item: AirPods
您可以在这里查看所有设计模式的实现。
GitHub 存储库
附注
我是刚开始写科技博客,如果您对我的写作有什么建议,或者有任何困惑的地方,请留言!
感谢您的阅读:)
以上是观察者模式的详细内容。更多信息请关注PHP中文网其他相关文章!