定义:定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
类型:创建型。
类的个数容易过多,增加复杂度,同时增加了系统的抽象性和理解难度
Video.java
package com.czh.creational.factorymethod;
public abstract class Video {
public abstract void play();
}
VideoFactory.java
package com.czh.creational.factorymethod;
public abstract class VideoFactory {
public abstract Video getVideo();
}
JavaVideo.java
package com.czh.creational.factorymethod;
public class JavaVideo extends Video {
@Override
public void play() {
System.out.println("播放Java视频");
}
}
JavaVideoFactory.java
package com.czh.creational.factorymethod;
public class JavaVideoFactory extends VideoFactory {
@Override
public Video getVideo() {
return new JavaVideo();
}
}
PythonVideo.java
package com.czh.creational.factorymethod;
public class PythonVideo extends Video {
@Override
public void play() {
System.out.println("播放Python视频");
}
}
PythonVideoFactory.java
package com.czh.creational.factorymethod;
public class PythonVideoFactory extends VideoFactory {
@Override
public Video getVideo() {
return new PythonVideo();
}
}
Test.java
package com.czh.creational.factorymethod;
public class Test {
public static void main(String[] args) {
VideoFactory videoFactory1 = new JavaVideoFactory();
Video video1 = videoFactory1.getVideo();
video1.play();
VideoFactory videoFactory2 = new PythonVideoFactory();
Video video2 = videoFactory2.getVideo();
video2.play();
}
}