定义:由一个工厂对象决定创建出哪一种产品类的实例
类型:创建型,但不属于GOF23种设计模式
工厂类负责创建的对象比较少
客户端(应用层)只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心
只需要传入一个正确的参数,就可以获取你所需要的对象,而无须知道其创建细节
工厂类的职责相对过重,增加新的产品时,需要修改工厂类的判断逻辑,违背开闭原则
Video.java
package com.czh.creational.simplefactory;
public abstract class Video {
public abstract void play();
}
JavaVideo.java
package com.czh.creational.simplefactory;
public class JavaVideo extends Video {
@Override
public void play() {
System.out.println("播放Java视频");
}
}
PythonVideo.java
package com.czh.creational.simplefactory;
public class PythonVideo extends Video {
@Override
public void play() {
System.out.println("播放Python视频");
}
}
VideoFactory.java
package com.czh.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;
}
}
Test.java
package com.czh.creational.simplefactory;
public class Test {
public static void main(String[] args) {
VideoFactory videoFactory = new VideoFactory();
Video video = videoFactory.getVideo("java");
if (video == null) {
return;
}
video.play();
}
}
Video.java
package com.czh.creational.simplefactory;
public abstract class Video {
public abstract void play();
}
JavaVideo.java
package com.czh.creational.simplefactory;
public class JavaVideo extends Video {
@Override
public void play() {
System.out.println("播放Java视频");
}
}
PythonVideo.java
package com.czh.creational.simplefactory;
public class PythonVideo extends Video {
@Override
public void play() {
System.out.println("播放Python视频");
}
}
VideoFactory.java
package com.czh.creational.simplefactory;
public class VideoFactory {
public Video getVideo(Class c) {
Video video = null;
try {
video = (Video) Class.forName(c.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return video;
}
}
Test.java
package com.czh.creational.simplefactory;
public class Test {
public static void main(String[] args) {
VideoFactory videoFactory = new VideoFactory();
Video video = videoFactory.getVideo(JavaVideo.class);
if (video == null) {
return;
}
video.play();
}
}