package com.yang.factory.simple;//静态工厂模式//增加一个新的产品,如果你不修改代码 ,做不到!//开闭原则 对于扩展开放,对于修改关闭publicclassCarfatory{// 方法一:publicstatic Car getCar(String car){if(car.equals("wuling")){returnnewwuling();}elseif(car.equals("tesla")){returnnewtesla();}else{return null;}}// 方法二publicstatic Car getwuling(){returnnewwuling();}publicstatic Car gettesla(){returnnewtesla();}publicstatic Car getdazhong(){returnnewdazhong();}}
package com.yang.factory.simple;import java.util.Date;publicclassteslaimplementsCar{@Overridepublicvoidname(){
Date a =newDate();
System.out.println(a);
System.out.println("tesla");}}
package com.yang.factory.simple;//工厂模式publicclassConsumer{publicstaticvoidmain(String [] args){// 接口实现所用的实现类,工厂// Car car1 = new wuling();// Car car2 = new tesla();// 2.使用工厂创建
Car car1 = Carfatory.getCar("wuling");
Car car2 = Carfatory.getCar("tesla");
car1.name();
car2.name();}}