1.本文以造车为例,写了1个接口,2个实现类,1个工厂类和1个客户端。示例代码如下:
package com.xiaobi.golf.factory;
public interface Car {
String run();
}
package com.xiaobi.golf.factory;
public class BydCar implements Car{
@Override
public String run() {
return "比亚迪汽车百公里加速只需要4.5秒!!";
}
}
package com.xiaobi.golf.factory;
public class AudiCar implements Car {
@Override
public String run() {
return "奥迪汽车百公里加速只需要3.6秒";
}
}
package com.xiaobi.golf.factory;
/**
* 简单工厂模式
*/
public class CarFactory {
public static Car createCar(String type){
if("奥迪".equals(type)){
return new AudiCar();
}else if ("比亚迪".equals(type)){
return new BydCar();
}else{
return null;
}
}
}
package com.xiaobi.golf.factory;
public class Client01 {
public static void main(String[]args){
Car car01=CarFactory.createCar("奥迪");
Car car02=CarFactory.createCar("比亚迪");
System.out.println(car01.run());
System.out.println(car02.run());
}
}