State设计模式:按照我的理解,State设计模式,最主要的用途就是消除代码
中过多的选择控制结构(if...elseif...else...和Switch case 结构)。因为含有
太多选择控制结构的代码不利于扩展和维护。
State设计模式定义:允许一个状态在改变其状态时,改变它的行为。我们将每
一种状态封装成一个单独的类,但所有的状态类需要有一个同一个规范(接口)
这样,运行时,根据传入的状态不同,表现不同的行为。
下面是从网上看到的一个例子,比较好理解。
<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:UseFELayout/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--> <!-- [if gte mso 10]> <mce:style><!-- /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --> <!-- [endif]-->
我们打篮球的时候运动员可以有正常状态,不正常状态,和超常状态,现在我们就
以我们打篮球时候投篮时候的状态来举例子,
首先我们抽象出状态,以及该状态下的行为,
interface State{
public void shot();
}
然后实现具体状态,我们这里有三个,三种状态三种行为。
不正常
public class AbnormalState implements State{
public void shot(){
System.out.println(" 今天你投篮十中一");
}
}
正常:
public class NormalState implements State{
public void shot(){
System.out.println(" 今天你投篮十中五");
}
}
超常:
public class SuperState implements State{
public void shot(){
System.out.println(" 今天你投篮十中十");
}
}
这个时候我们来一个环境,一个运动员, 正常情况下是正常状态
public class Player{
private State state=new NormalState();
public void setState(State state){
this.state=state;
}
public void shot(){
state.shot();// 这里我感觉是创建型模式的适配器模式,对象适配 应该就是这样,
}
}
测试这个例子
public class StateTest
{
public static void main(String[] args){
Player player=new Player();
player.shot();// 正常下投篮
player.setState(new NonormalState());
player.shot(); 不正常下投篮
player.setState(new SuperState());
player.shot(); 超常下投篮
}
}
使用状态模式的好处是每个状态被封装到一个独立的类中,这些类可以独立变
化,而主对象中没有繁琐的swich-case 语句,并且添加新的状态非常容易,只需
要从State 派生一个新类即可。