title: mvc模式
layout: pattern
title: Model-View-Controller
folder: model-view-controller
categories: Presentation Tier
tags:

  • Java
  • Difficulty-Intermediate

总结

Separate the user interface into three interconnected components:
the model, the view and the controller. Let the model manage the data, the view
display the data and the controller mediate updating the data and redrawing the
display.

设计类图

  • 实际案例
    alt text

  • 设计方案
    alt text

使用方法

mvc是一个框架模式,它使应用程序的输入,处理和输出分开,最典型的MVC就是JSP + servlet + javabean的模式,主要优点:分离视图层和业务逻辑层也使得WEB应用更易于维护和修改

观察者模式

定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到
通知并自动更新

UML图和详细介绍

自定义方式

alt text

  • 通过 Weather主题接口中的addObserver注册为观察者
  • 其中WeatherType为具体的天气类型
    public enum WeatherType {

    SUNNY, RAINY, WINDY, COLD;

    @Override
    public String toString() {
    return this.name().toLowerCase();
    }
    }

  • WeatherObserver具体的观察者可以是实现此接口的任意类。

public interface WeatherObserver {

/**

  • 更新
  • @param currentWeather
    */
    void update(WeatherType currentWeather);

}

通过java中Observer类库实现

public abstract class Observable, O extends Observer, A> {

protected List observers;

public Observable() {
this.observers = new CopyOnWriteArrayList<>();
}

public void addObserver(O observer) {
this.observers.add(observer);
}

public void removeObserver(O observer) {
this.observers.remove(observer);
}

/**

  • Notify observers
    */
    @SuppressWarnings(“unchecked”)
    public void notifyObservers(A argument) {
    for (O observer : observers) {
    observer.update((S) this, argument);
    }
    }
    }
  • 在java中还有很多地方用到了观察者模式,比如在IO中,javaBeans,其中观察者模式在对象之间定义
    一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新