1 public class Test{ 2 3 public static void main(String[] args) { 4 Context ctx1 = new Context(); 5 ctx1.setWeather(new Sunshine()); 6 System.out.println(ctx1.weatherMessage()); 7 8 System.out.println("==============="); 9 10 Context ctx2 = new Context(); 11 ctx2.setWeather(new Rain()); 12 System.out.println(ctx2.weatherMessage()); 13 } 14 } 1 public class Context { 2 3 private Weather weather; 4 5 public void setWeather(Weather weather) { 6 this.weather = weather; 7 } 8 9 public Weather getWeather() { 10 return this.weather; 11 } 12 13 public String weatherMessage() { 14 return weather.getWeather(); 15 } 16 } 1 public interface Weather { 2 3 String getWeather(); 4 } 1 public class Rain implements Weather { 2 3 public String getWeather() { 4 return "下雨"; 5 } 6 } public class Sunshine implements Weather { public String getWeather() { return "阳光"; } }
看了这个设计模式,感觉抽象级别高。不断学习中。。。
转载于:https://www.cnblogs.com/huzi007/p/3899568.html