简单工厂、工厂方法和抽象工厂的区别:
简单工厂:小作坊,不符合开闭原则
工厂模式:工厂流水线,专人专用
抽象工厂模式:产品族,描述了一系列的产品,但不符合开闭原则,产品族中扩展新的产品困难,需要修改抽象工厂的接口
简单工厂:
public interface ICourse {
/** 录制视频 */
public void record();
}
//创建一个 Java 课程的实现 JavaCourse 类:
public class JavaCourse implements ICourse {
public void record() {
System.out.println("录制 Java 课程");
}
//增加课程 PythonCourse 类:
public class PythonCourse implements ICourse {
public void record() {
System.out.println("录制 Python 课程");
}
}
//创建 CourseFactory 工厂类:
public class CourseFactory {
public ICourse create(String name){
if("java".equals(name)){
return new JavaCourse();
}else if("python".equals(name)){
return new PythonCourse();
}else {
return null;
}
}
}
//客户端调用代码:
public class SimpleFactoryTest {
public static void main(String[] args) {
CourseFactory factory = new CourseFactory();
factory.create("java");
}
}
工厂模式:
//ICourseFactory 接口:
public interface ICourseFactory {
ICourse create();
}
//在分别创建子工厂,JavaCourseFactory 类:
public class JavaCourseFactory implements ICourseFactory {
public ICourse create() {
return new JavaCourse();
}
//PythonCourseFactory 类:
public class PythonCourseFactory implements ICourseFactory {
public ICourse create() {
return new PythonCourse();
}
}
//看测试代码:
public static void main(String[] args) {
ICourseFactory factory = new PythonCourseFactory();
ICourse course = factory.create();
course.record();
factory = new JavaCourseFactory();
course = factory.create();
抽象工厂:
//IVideo 接口:
public interface IVideo {
void record();
}
//INote 接口:
public interface INote {
void edit();
//然后创建一个抽象工厂 CourseFactory 类:
import com.gupaoedu.vip.pattern.factory.INote;
import com.gupaoedu.vip.pattern.factory.IVideo;
/**
* 抽象工厂是用户的主入口
* 在 Spring 中应用得最为广泛的一种设计模式
* 易于扩展
* Created by Tom.
*/
public interface CourseFactory {
INote createNote();
IVideo createVideo();
}
//接下来,创建 Java 产品族,Java 视频 JavaVideo 类:
public class JavaVideo implements IVideo {
public void record() {
System.out.println("录制 Java 视频");
}
}
//扩展产品等级 Java 课堂笔记 JavaNote 类:
public class JavaNote implements INote {
public void edit() {
System.out.println("编写 Java 笔记");
}
}
//创建 Java 产品族的具体工厂 JavaCourseFactory:
public class JavaCourseFactory implements CourseFactory {
public INote createNote() {
return new JavaNote();
}
public IVideo createVideo() {
return new JavaVideo();
}
}
//然后创建 Python 产品,Python 视频 PythonVideo 类:
public class PythonVideo implements IVideo {
public void record() {
System.out.println("录制 Python 视频");
}
}
//扩展产品等级 Python 课堂笔记 PythonNote 类:
public class PythonNote implements INote {
public void edit() {
System.out.println("编写 Python 笔记");
}
}
//创建 Python 产品族的具体工厂 PythonCourseFactory:
public class PythonCourseFactory implements CourseFactory {
public INote createNote() {
return new PythonNote();
}
public IVideo createVideo() {
return new PythonVideo();
}
}
//来看客户端调用:
public static void main(String[] args) {
JavaCourseFactory factory = new JavaCourseFactory();
factory.createNote().edit();
factory.createVideo().record();
}