java 电梯

import java.util.Scanner;
interface State{
     void handle();
     void up();
     void down();
     void open();
     void close();
     void warning();
     void removeWarning();
} 

class OpenState implements State{
	Context context=new Context();
    public void handle(){
       System.out.println("电梯门打开中");
    }
    public void up() {
    	System.out.println("电梯门开启中不可移动");
    }
    public void down() {
    	System.out.println("电梯门开启中不可移动");
    }
    public void open() {
    }
    public void close() {
       System.out.println("电梯门关上了");
       context.setState(new CloseState());
    }
    public void warning() {
    	System.out.println("超重警告");
    	context.setState(new WarningState());
    }
    public void removeWarning() {
    	
    }

}   
class CloseState implements State{
	Context context=new Context();
    public void handle(){
       System.out.println("电梯门关闭中");
    }
    public void up() {
       System.out.println("电梯上升了");
       open();
    }
    public void down() {
    	System.out.println("电梯下降了");
    	open();
    }
    public void open() {
    	System.out.println("开门");
    	context.setState(new OpenState());
    }
    public void close() {
    	
    }
    public void warning() {
    	
    }
    public void removeWarning() {
    	
    }
} 
class WarningState implements State{
	Context context=new Context();
    public void handle(){
        System.out.println("电梯超重中");
     }
     public void up() {
        System.out.println("超重中不允许移动");
     }
     public void down() {
     	System.out.println("超重中不允许移动");  	
     }
     public void open() {

     }
     public void close() {
     	System.out.println("超重状态中不允许关门");
     }
     public void warning() {
     	
     } 
     public void removeWarning() {
        System.out.println("解除了警报状态,进入开门状态");
        context.setState(new OpenState());
     }
}


class Context{
    private State state;
    //1开启  2关闭 3上升 4下降  5超重 6解除超重  -1结束  
	void fun() {
    int i=0;
	while(i!=-1) {
		Scanner scanner = new Scanner(System.in);
		i=scanner.nextInt();
		switch(i) {
		case 1:state.open();break;
		case 2:state.close();break;
		case 3:state.up();break;
		case 4:state.down();break;
		case 5:state.warning();break;
		case 6:state.removeWarning();break;
		}
	}
	System.exit(0);
}	
	public void setState(State  s ){
       System.out.println("电梯状态已被修改");
        state = s;
        state.handle();
        fun();
   } 
}

public class Client {
	 public static void main(String[] args) {
	        Context context=new Context();
	         context.setState(new OpenState());   //初始默认门打开
	  
	 }
}	        	         


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页