我目前正在研究观察者模式,我遇到了一些困惑。
当我阅读这行代码时:
IObserverSubscribe user1= new ConcreteObserverYoutubeUser();
我认为界面IObserverSubscribe user1
正在创建和实例化new ConcreteObserverYoutubeUser()
。这让我有点困惑,因为通常被声明的同一个类也在实例化。应该是这样的:
IObserverSubscribe user1= new IObserverSubscribe();
为什么界面装饰能够实例化另一个类?
完整代码如下:
主要的:
package observerpattern;
public class ObserverPattern {
/**
* The observer pattern is a software design pattern in which
* an object, called the subject, maintains a list of its dependents,
* called observers, and notifies them automatically of any
* state changes, usually by calling one of their methods.
* It is mainly used to implement distributed event handling systems.
* The Observer pattern is also a key part in the familiar
* Model View Controller (MVC) architectural pattern.
*/
public static void main(String[] args) {
SubjectYouTubeChannel sytc= new SubjectYouTubeChannel();// create youtube channel
IObserverSubscribe user1= new ConcreteObserverYoutubeUser();
IObserverSubscribe user2= new ConcreteObserverYoutubeUser();
IObserverSubscribe moderator1= new ConcreteObserverYoutubeModerator();
sytc.Subscribe(user1);
sytc.Subscribe(user2);
sytc.Subscribe(moderator1);
sytc.Unsubscribe(user2);
sytc.notifySubscribers();
}
}
学科:
package observerpattern;
import java.util.ArrayList;
import java.util.List;
import observerpattern.IObserverSubscribe;
public class SubjectYouTubeChannel {
private List<IObserverSubscribe> subscribers = new ArrayList<IObserverSubscribe>();
public void Subscribe(IObserverSubscribe ios){
subscribers.add(ios);
}
public void Unsubscribe(IObserverSubscribe ios){
subscribers.remove(ios);
}
public void notifySubscribers(){
for(IObserverSubscribe ios : subscribers ){
ios.Notify();
}
}
}
界面观察者:
package observerpattern;
public interface IObserverSubscribe {
void Notify();
}
具体观察者:
package observerpattern;
public class ConcreteObserverYoutubeUser implements IObserverSubscribe{
@Override
public void Notify() {
System.out.println("User watches video, comments, ect");
}
}