恋爱过程中的设计模式之状态模式

状态模式,根据状态的不同,则行为不同
package com.fruitking.designparten.state;

public interface LoveState {
	
	public static final String UNKOWN = "unkown";//不认识的
	public static final String WOOING = "wooing";//追求中
	public static final String MARRIAGED = "marriaged";//已结婚
	
	public void run();//现在能做的事情
	public void next();//下一步能达到什么状态

}

package com.fruitking.designparten.state;

public class UnkownState implements LoveState {

	private Gentleman gentleman;
	
	public UnkownState(Gentleman gentleman){
		this.gentleman = gentleman;
	}
	
	public void next() {
		gentleman.changeState(new WooingState(this.gentleman));
	}

	public void run() {
		System.out.println("只能远远的看着她,其它事情啥都不能做...");
	}

}

package com.fruitking.designparten.state;

public class WooingState implements LoveState {

	private Gentleman gentleman;
	
	public WooingState(Gentleman gentleman){
		this.gentleman = gentleman;
	}
	
	public void next() {
		gentleman.changeState(new MarriagedState(this.gentleman));
	}

	public void run() {
		System.out.println("可以邀请她一起吃饭,看电影,散步...");
	}

}

package com.fruitking.designparten.state;

public class MarriagedState implements LoveState {

	private Gentleman gentleman;
	
	public MarriagedState(Gentleman gentleman){
		this.gentleman = gentleman;
	}
	
	public void next() {
		System.out.println("结婚了就不能离婚啦,要永远在一起!");
		System.out.println(gentleman.toString());
	}

	public void run() {
		System.out.println("亲吻...");
	}

}

package com.fruitking.designparten.state;

public class Gentleman {
	
	private LoveState loveState;
	
	public Gentleman(){
		loveState = new UnkownState(this);
	}
	
	public void changeState(LoveState loveState){
		this.loveState = loveState;
	}
	
	public void doSomething(){
		this.loveState.run();
		this.loveState.next();
	}

}

package com.fruitking.designparten.state;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Gentleman gentleman = new Gentleman();
		gentleman.doSomething();
		gentleman.doSomething();
		gentleman.doSomething();
	}
}

你可能感兴趣的:(java,设计模式)