定义
由一个工厂对象决定创建出哪一种产品类的实例。
属于创建型,但不属于GOF23种设计模式。
适用场景
工厂类负责创建的对象比较少
客户端只知道传入工厂类的参数,不关心创建对象的具体逻辑。
优点
只需要传入一个正确的参数,就可以获取你所需要的对象,而无需知道其创建细节。
缺点
工厂类的职责相对过重,增加新的产品需要修改工厂类的判断逻辑,违背开闭原则。
Coding
错误代码
package design.creational.simplefactory;
public abstract class Video {
public abstract void produce();
}
package design.creational.simplefactory;
public class JavaVideo extends Video {
@Override
public void produce() {
System.out.println("这是Java视频课程");
}
}
package design.creational.simplefactory;
public class PythonVideo extends Video {
@Override
public void produce() {
System.out.println("这是Python视频课程");
}
}
package design.creational.simplefactory;
public class Test {
public static void main(String[] args) {
// 此时Test类依赖于JavaVideo类或PythonVideo类
Video video = new JavaVideo();
video.produce();
}
}
正确代码(但违背开闭原则)
package design.creational.simplefactory;
public class VideoFactory {
public Video getVideo(String type) {
if ("Java".equalsIgnoreCase(type)) {
return new JavaVideo();
} else if ("Python".equalsIgnoreCase(type)) {
return new PythonVideo();
}
return null;
}
}
package design.creational.simplefactory;
public class JavaVideo extends Video {
@Override
public void produce() {
System.out.println("这是Java视频课程");
}
}
package design.creational.simplefactory;
public class PythonVideo extends Video {
@Override
public void produce() {
System.out.println("这是Python视频课程");
}
}
package design.creational.simplefactory;
public class Test {
public static void main(String[] args) {
VideoFactory videoFactory = new VideoFactory();
Video video = videoFactory.getVideo("Java");
video.produce();
}
}
正确代码
package design.creational.simplefactory;
public class VideoFactory {
// public Video getVideo(String type) {
// if ("Java".equalsIgnoreCase(type)) {
// return new JavaVideo();
// } else if ("Python".equalsIgnoreCase(type)) {
// return new PythonVideo();
// }
// return null;
// }
public Video getVideo(Class c) {
Video video = null;
try {
video = (Video) Class.forName(c.getName()).newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return video;
}
}
package design.creational.simplefactory;
public class Test {
public static void main(String[] args) {
// VideoFactory videoFactory = new VideoFactory();
// Video video = videoFactory.getVideo("Java");
// video.produce();
VideoFactory videoFactory = new VideoFactory();
Video video = videoFactory.getVideo(JavaVideo.class);
video.produce();
}
}