工厂方法模式

工厂方法模式

定义与类型

定义:工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。属于创建型

适用场景

  • 创建对象需要大量的代码
  • 客户端不需要知道产品类型如何创建的细节
  • 一个类通过其子类来指定创建哪个对象

    优点

  • 用户只需要关心产品所对应的工程无需关心细节
  • 加入新产品符合开闭原则,提高可扩展性

    缺点

  • 类的个数增多,增加了系统的复杂性
  • 增加了系统的抽象性和可理解性

场景例子

教学视频工厂
视频抽象类

UML

代码
1
2
3
4
5
6
7
8
9
10
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:
* @ Date: Created in 15:33 2018-11-26
* @ Author: Anthony_Duan
*/
public abstract class Video {
public abstract void produce();
}

基于video抽象类的具体实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:
* @ Date: Created in 15:34 2018-11-26
* @ Author: Anthony_Duan
*/
public class JavaVideo extends Video {

@Override
public void produce() {
System.out.println("录制Java课程视频");

}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:
* @ Date: Created in 15:37 2018-11-26
* @ Author: Anthony_Duan
*/
public class PythonVideo extends Video {
@Override
public void produce() {
System.out.println("录制Python课程视频");
}
}

视频类的工厂方法,这里一般是一个抽象类,因为要将创建方法交给其子类实现

1
2
3
4
5
6
7
8
9
10
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:工厂模式
* @ Date: Created in 15:39 2018-11-26
* @ Author: Anthony_Duan
*/
public abstract class VideoFactory {
abstract Video getVideo();
}

具体实现的工厂子类

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:
* @ Date: Created in 17:06 2018-11-26
* @ Author: Anthony_Duan
*/
public class JavaVideoFactory extends VideoFactory {
@Override
Video getVideo() {
return new JavaVideo();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description:
* @ Date: Created in 17:06 2018-11-26
* @ Author: Anthony_Duan
*/
public class PythonVideoFactory extends VideoFactory {


@Override
Video getVideo() {
return new PythonVideo();
}
}

工厂方法测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.anthony.design.pattern.creational.factorymethod;

/**
* @ Description: 工厂方法测试类
* @ Date: Created in 15:41 2018-11-26
* @ Author: Anthony_Duan
*/
public class test {
public static void main(String[] args) {
VideoFactory videoFactory = new JavaVideoFactory();
VideoFactory videoFactory2 = new PythonVideoFactory();
Video video = videoFactory.getVideo();
Video video2 = videoFactory2.getVideo();
video.produce();
video2.produce();
}
}

-------------End Of This ArticleThank You For Reading-------------