状态模式

本文介绍状态模式的概念,通过天气变化的例子展示如何使用状态模式来实现对象内部状态改变时的行为变化。状态模式允许对象在其内部状态改变时改变其行为,使对象看起来像是修改了它的类。

状态模式:允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。以下是例子:

public interface Weather {  

String getWeather(); }

 

public class Rain implements Weather {  

public String getWeather() { return "下雨"; } }

 

public class Sunshine implements Weather {  

public String getWeather() { return "阳光"; } }

 

public class Context {  

private Weather weather;

public void setWeather(Weather weather){

this.weather = weather; }

public Weather getWeather(){

return weather; }

public String weatherMessage(){

return weather.getWeather(); } }

 

//测试类

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()); } }

转载于:https://www.cnblogs.com/lee0oo0/archive/2012/06/08/2542020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值