简单工厂模式:
打开支付宝扫一扫 ,对着共享单车的二维码 ,就可以打开共享单车
用代码来展示就是:
public enum BikeCompany { OFO,//ofo HELLOBIKE//哈罗单车}
//共享单车都有各自的开锁声音public interface Bike { public void unlock();}
//哈罗单车public class HelloBike implements Bike { @Override public void unlock() { // TODO Auto-generated method stub System.out.println("hello bike"); } }
//小黄车public class OFO implements Bike{ @Override public void unlock() { // TODO Auto-generated method stub System.out.println("滴滴滴"); }}
/** * 支付宝扫一扫 * 工厂 * */public class AlipayRichScan { public static Bike getBike(BikeCompany bikeCompany){ switch (bikeCompany) { case OFO: return new OFO(); case HELLOBIKE: return new HelloBike(); default: return null; } }}
运行一下程序
public class BikeTest { public static void main(String[] args) { Bike bike = AlipayRichScan.getBike(BikeCompany.HELLOBIKE); bike.unlock();//开锁声音 }}
输出结果:
hello bike
UML类图:
如果摩拜单车也加入了支付宝,那得修改不少东西哦... 比如enum(BikeCompany)增加摩拜单车公司,
AlipayRichScan要增加case,有没有更好的办法呢?