创建手机规范类(接口)
public interface Phone {void make();}
小米手机制造商(继承手机规范接口)
public class MiPhone implements Phone {public MiPhone() {this.make();}@Overridepublic void make() {// TODO Auto-generated method stubSystem.out.println("make xiaomi phone!");}}
苹果手机制造商
public class IPhone implements Phone {public IPhone() {this.make();}@Overridepublic void make() {// TODO Auto-generated method stubSystem.out.println("make iphone!");}}
手机代加工工厂
public class PhoneFactory {public Phone makePhone(String phoneType) {if(phoneType.equalsIgnoreCase("MiPhone")){return new MiPhone();}else if(phoneType.equalsIgnoreCase("iPhone")) {return new IPhone();}return null;}}
测试类
public class Demo {public static void main(String[] arg) {PhoneFactory factory = new PhoneFactory();Phone miPhone = factory.makePhone("MiPhone"); // make xiaomi phone!IPhone iPhone = (IPhone)factory.makePhone("iPhone"); // make iphone!}}
