在某一场景需要有多种情况,不同情况有不同的处理(大量 if-else 或者 switch),但大致功能是一样的,这时我们可以考虑用策略模式实现。
在 RecyclerView 还没火起来前,ListView 是一个很重要的组件,我们通常在布局里写个 ListView 组件,然后在代码中 setAdapter,把 View 与 Model 结合的任务交给了 Adapter。
1:首先定义一个接口 public interface NumberPrice{ public float getPrice(float price); } 2:定义三个实现类 public class NumberPrice1 implements NumberPrice{ private float getPrice(float price){ reture price*0.9; }; } public class NumberPrice2 implements NumberPrice{ private float getPrice(float price){ return price*0.8; }; } public class NumberPrice3 implements NumberPrice{ private float getPrice(float price){ return price*0.7; }; } 3.定义一个策略类 public class Price{ private NumberPrice numberPrice; public void price(NumberPrice numberPrice){ this.numberPrice=numberPrice; } private float getPrice(float price){ numberPrice.getPrice(price); } 4.定义一个客户端 public void client{ private float 100; NumberPrice numberPrice=new numberPrice1(); price pri=new price(numberPrice); pri.getPrice(100); }
原文:http://www.cnblogs.com/nbls/p/7192597.html