定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
package com.lyz.design.state;
/**
* Context
* @author binghe
*
*/
public class Context {
private Weather weather;
public void setWeather(Weather weather) {
this.weather = weather;
}
public Weather getWeather() {
return this.weather;
}
public String weatherMessage() {
return weather.getWeather();
}
}
package com.lyz.design.state;
/**
* State
* @author binghe
*
*/
public interface Weather {
String getWeather();
}
package com.lyz.design.state;
/**
* ConcreteStatesubclasses
* @author binghe
*
*/
public class Rain implements Weather {
public String getWeather() {
return "下雨";
}
}
Sunshine
package com.lyz.design.state;
/**
* ConcreteStatesubclasses
* @author binghe
*
*/
public class Sunshine implements Weather {
public String getWeather() {
return "阳光";
}
}
package com.lyz.design.state;
/**
* Test
* @author binghe
*
*/
public class Test{
public static void main(String[] args) {
Context ctx1 = new Context();
ctx1.setWeather(new Sunshine());
System.out.println(ctx1.weatherMessage());
System.out.println("===============");
Context ctx2 = new Context();
ctx2.setWeather(new Rain());
System.out.println(ctx2.weatherMessage());
}
}
阳光
===============
下雨