标签:print sys comm server1 pack out .sh code system
状态模式,随着状态的改变,其行为也会随之改变。也可以用来解决大量if else分支机构问题。
实例代码:
package com.shi.common; public class StatePattern { public static void main(String[] args) { Server1 server1 = new Server1(); String result = server1.getServer(2); System.out.println(result); result = server1.getServer(1); System.out.println(result); result = server1.getServer(3); System.out.println(result); result = server1.getServer(4); System.out.println(result); } } interface State{ public String getServer(int state); } class Server1 implements State{ @Override public String getServer(int state) { if (state == 1) { return "服务器1,为您服务"; }else{ return new Server2().getServer(state); } } } class Server2 implements State{ @Override public String getServer(int state) { if (state == 2) { return "服务器2,为您服务"; }else{ return new Server3().getServer(state); } } } class Server3 implements State{ @Override public String getServer(int state) { if (state == 3) { return "服务器3,为您服务"; }else{ return "未找到服务器"; } } }
输出结果:
服务器2,为您服务
服务器1,为您服务
服务器3,为您服务
未找到服务器
标签:print sys comm server1 pack out .sh code system
原文地址:http://www.cnblogs.com/lay2017/p/7672553.html