简单工厂模式与工厂方法模式
简单工厂模式与工厂方法模式
简单工厂模式
优点:简单,代码量少,清晰
缺点:新增一个产品,工厂的代码不能做到零修改
工厂方法模式
优点:新增一个产品,代码可以做到零修改,只做扩展
缺点:代码量过多,繁杂
注意:实践中还是简单工厂模式更好用
简单工厂模式代码
package com.example.designPattern23.factory.simple;
public class car {
}
package com.example.designPattern23.factory.simple;
public class Tesla extends car {
public Tesla() {
System.out.println("特斯拉");
}
}
package com.example.designPattern23.factory.simple;
public class Wuling extends car {
public Wuling() {
System.out.println("五菱");
}
}
package com.example.designPattern23.factory.simple;
public class CarFactory {
private String name;
public CarFactory(String name) {
this.name = name;
}
public static Object get(String name) {
if (name.equals("Wuling")) {
return new Wuling();
} else if (name.equals("Tesla")) {
return new Tesla();
} else {
return null;
}
}
}
package com.example.designPattern23.factory.simple;
public class Consumer {
public static void main(String[] args) {
CarFactory.get("Tesla");
CarFactory.get("Wulin");
}
}
输出
特斯拉
五菱
工厂方法模式
package com.example.designPattern23.factory.method;
public class car {
}
package com.example.designPattern23.factory.method;
public class Tesla extends car {
public Tesla() {
System.out.println("特斯拉");
}
}
package com.example.designPattern23.factory.method;
public class TeslaFactory {
public void get() {
System.out.println("特斯拉");
}
}
package com.example.designPattern23.factory.method;
public class Wuling extends car {
public Wuling() {
System.out.println("五菱");
}
}
package com.example.designPattern23.factory.method;
public class WulingFactory {
public void get() {
System.out.println("五菱");
}
}
package com.example.designPattern23.factory.method;
public class Consumer {
public static void main(String[] args) {
TeslaFactory teslaFactory = new TeslaFactory();
WulingFactory wulingFactory = new WulingFactory();
teslaFactory.get();
wulingFactory.get();
}
}
输出
特斯拉
五菱