简单工厂:一个工厂只能处理一个对象
public class CourseFactory {
public ICourse create(Class<? extends ICourse> clazz){
try {
if (null != clazz) {
return clazz.newInstance();
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
抽象工厂:类似于List与ArrayList的关系
public interface CourseFactory {
INote createNote();
IVideo createVideo();
}
public class JavaCourseFactory implements CourseFactory {
public INote createNote() {
return new JavaNote();
}
public IVideo createVideo() {
return new JavaVideo();
}
}
public class PythonCourseFactory implements CourseFactory {
public INote createNote() {
return new PythonNote();
}
public IVideo createVideo() {
return new PythonVideo();
}
}
public class AbstractFactoryTest {
public static void main(String[] args) {
JavaCourseFactory factory = new JavaCourseFactory();
factory.createNote().edit();
factory.createVideo().record();
}
}
public interface INote {
void edit();
}
public interface IVideo {
void record();
}
public class JavaNote implements INote {
public void edit() {
System.out.println("编写Java笔记");
}
}
public class JavaVideo implements IVideo {
public void record() {
System.out.println("录制Java视频");
}
}
public class PythonNote implements INote {
public void edit() {
System.out.println("编写Python笔记");
}
}
public class PythonVideo implements IVideo {
public void record() {
System.out.println("录制Python视频");
}
}