HeadFirst设计模式_读书笔记_010_状态模式

阅读更多

状态模式:允许对象在内部状态改变的时候改变它的行为。

HeadFirst设计模式_读书笔记_010_状态模式_第1张图片

 

例如: 我们在12306上买票,行为是卖票,状态有两个,有余票则出票成功,余票不足就出票失败。

public class Station {

	public State state;
	private int tickets = 0;
	public Station(int tickets)
	{
		this.tickets = tickets;
		if(tickets>0)
		{
			state = new HasTicketState(this);
		}
	}
	
	public void soldTickets()
	{
		state.soldTicket();
	}
	
	public void setTickets(int tickets)
	{
		this.tickets = tickets;
		if(tickets>0)
		{
			state = new HasTicketState(this);
		}

	}
	
	public int getTickets()
	{
		return this.tickets;
	}
	
	public void setState(State sta)
	{
		this.state = sta;
	}

}

 

public abstract class State {
	
	public abstract void soldTicket();
	

}

 

public class NoTicketState extends State{

	@Override
	public void soldTicket() {
	   System.out.println("没有余票,出票失败");
	}

}

 

public class HasTicketState extends State{
	private Station station;
	public HasTicketState(Station sta)
	{
		this.station = sta;
	}
	
	@Override
	public void soldTicket() {
		station.setTickets(station.getTickets()-1);
		System.out.println("出票成功,余票" + station.getTickets()+"张");
		if(station.getTickets() == 0)
		{
			this.station.setState(new NoTicketState());
		}
		
	}

}

 

	public static void main(String args[])
	{
		Station sta = new Station(3);
		sta.soldTickets();
		sta.soldTickets();
		sta.soldTickets();
		sta.soldTickets();
		sta.setTickets(10);
		sta.soldTickets();
		sta.soldTickets();
	}
}

 
 

  • HeadFirst设计模式_读书笔记_010_状态模式_第2张图片
  • 大小: 3.4 KB
  • 查看图片附件

你可能感兴趣的:(java,状态模式)