本文个人博客地址:https://abeille.top/blog/detail/AT815YDW7
工厂模式分三种:简单工厂模式、工厂方法模式、抽象工厂模式;
首先定义一个课程标准接口;
public interface ICourse {
/** 录制视频 */
void record ();
}
定义接口的实现:
public class JavaCourse implements ICourse {
@Override
public void record () {
System.out.println(“java 课程”);
}
}
public class PythonCourse implements ICourse {
@Override
public void record () {
System.out.println(“python 课程”);
}
}
创建工厂类:
public class CourseFactory {
public ICourse create (Class<? Extends ICourse> clazz) {
try {
if (null != clazz) {
return clazz.newInstance(); // 通过反射获取类的实例
}
} catch () {
e.printStackTree();
}
}
}
调用示例:
public class SimpleFactoryExample {
public static void main (String[] args) {
CourseFactory factory = new CourseFacotry();
ICourse course = factory.create(JavaCourse.class);
course.record();
}
}
这里涉及到一个概念——::开闭原则:::软件实体应当对扩展开放,对修改关闭(Software entities should be open for extension,but closed for modification);
创建工厂接口:
public interface ICourseFactory {
/** 录制视频 */
ICourse create ();
}
创建子工厂类:
public class JavaCourseFactory implements ICourseFactory {
@Override
public ICourse create () {
return new JavaCourse();
}
}
public class PythonCourseFactory implements ICourseFactory {
@Override
public ICourse create () {
return new PythonCourse();
}
}
调用示例:
public class FactoryMethodExample {
public static void main (String[] args) {
ICourseFactory factory = new JavaCourseFacotry();
ICourse course = factory.create();
course.record();
}
}
工厂方法模式适用的场景:
增加视频录制、文档编写接口;
public interface IVideo {
void record ();
}
public interface INote {
void edit ();
}
创建实现类:
public class JavaVideo implements IVideo {
@Override
public void record () {
System.out.println(“Java视频课”);
}
}
public class PythonVideo implements IVideo {
@Override
public void record () {
System.out.println(“Python视频课”);
}
}
public class JavaNote implements INote {
@Override
public void edit () {
System.out.println(“Java笔记”);
}
}
public class PythonNote implements INote {
@Override
public void edit () {
System.out.println(“Python笔记”);
}
}
创建抽象工厂类:
public interface ICourseFactory {
IVideo createVideo ();
INote createNote ();
}
创建java产品族的具体工厂:
public class JavaCourseFactory implements ICourseFactory {
@Override
public IVideo createVideo () {
return new JavaVideo ();
}
@Override
public INote createNote () {
return new JavaNote ();
}
}
创建Python产品族的具体工厂:
public class PythonCourseFactory implements ICourseFactory {
@Override
public IVideo createVideo () {
return new PythonVideo ();
}
@Override
public INote createNote () {
return new PythonNote ();
}
}
调用示例:
public class AbsFactoryExample {
ICourseFactory factory = new JavaCourseFactory();
factory.createVideo().record();
factory.createNote().edit();
}
抽象工厂模式的缺点: