场景:饭店收银,1现金,2刷卡,3微信
首先定一个收费的接口
public interface ShouFei { /** * 收费 */ void shoufei(); }
有接口就有实现类:下面3个实现类
public class XianJIn implements ShouFei { @Override public void shoufei() { System.out.println("现金支付"); } }
public class ShuaKa implements ShouFei { @Override public void shoufei() { System.out.println("刷卡支付"); } }
public class WeiXin implements ShouFei { @Override public void shoufei() { System.out.println("微信支付"); } }
接下来定一个类用于封装这个收费
public class FuKuan { ShouFei shouFei; public FuKuan(ShouFei shouFei) { this.shouFei = shouFei; } public void shouFei() { shouFei.shoufei(); } }
接下来是主方法
public class Qiantai { public static void main(String[] args) { shoufei(1); shoufei(2); shoufei(3); } /** * 1,现金,2刷卡,3微信 * * @param type */ public static void shoufei(int type) { FuKuan fuKuan = null; if (type == 1) { fuKuan = new FuKuan(new XianJIn()); } else if (type == 2) { fuKuan = new FuKuan(new ShuaKa()); } else if (type == 3) { fuKuan = new FuKuan(new WeiXin()); } fuKuan.shouFei(); } }
这样,我只需要在处理我的逻辑的时候知道支付的类型就调用不同的方法,扩展的时候只需要添加一个实现类和在主方法的收费这个方法里添加一个类型就可以了.