RedCloud Help

工厂模式

工厂模式

工厂方法模式

简单工厂模式

抽象工厂模式

简单工厂模式

create
create
«interface»
ICourse
record()
«class»
JavaCourse
record()
«class»
PythonCourse
record()
«class»
CourseFactory
create(String name) : ICourse
  • 缺点:

    • 类的个数容易过多,增加复杂度。

    • 增加了系统的抽象性和理解难度。

工厂方法模式

  • 简单工厂的模式的改造

«interface»
ICourseFactory
create() : ICourse
PythonCourseFactory
create() : ICourse
JavaCourseFactory
create() : ICourse
«interface»
ICourse
record() : void
PythonCourse
record() : void
JavaCourse
record() : void
  • 经典框架logback中工厂方法的应用:

«interface»
ILoggerFactory
getLogger(string) : Logger
«class»
SubsituteLoggerFactory
getLogger(string) : Logger
getLoggerName() : List
«class»
NOPLoggerFactory
getLogger(string) : Logger
«class»
Log4jLoggerFactory
getLogger(string) : Logger
«interface»
Logger
«interface»
LocationAwareLogger
«class»
NamedLoggerBase
«class»
MarkerIgnoringBase
«class»
Log4jLoggerAdapter
«class»
NOPLogger

抽象工厂模式

  • 简单例子:

create
create
ask
ask
«interface»
Animal
+getType() : String
+makeSound() : String
Duck
+getType() : String
+makeSound() : String
Dog
+getType() : String
+makeSound() : String
Bear
+getType() : String
+makeSound() : String
«interface»
Color
+getColor() : String
White
+getColor() : String
Brown
+getColor() : String
Black
+getColor() : String
ColorFactory
+create() : Color
AnimalFactory
+create() : Animal
«interface»
AbstractFactory
+create() : T
FacotryProvider
+getFactory() : AbstractFactory
Client
+main() : void
  • 课程小例子

create
create
create
create
«interface»
IVideo
record() : void
«interface»
INote
edit() : void
«interface»
CourseFactory
createNote() : INote
createVideo() : IVideo
JavaNote
edit() : void
JavaVideo
record() : void
JavaCourseFactory
createNote() : INode
creatVedio() : IVedio
PythonNote
edit() : void
PythonVideo
record() : void
PythonCourseFactory
createNote() : INode
creatVedio() : IVedio
  • 缺点

    • 规定了所有可能被创建的产品集合,产品族中扩展新的产品困难,需要修改抽象工厂的接口

    • 增加了系统的抽象性和理解难度

      • 但在实际应用中,我们千万不要犯强迫症甚至有洁癖。在实际需求中产品等级结构升级是非常正常的事情。我们可以根据实际情况,只要不是频繁升级,可以不遵循开闭原则。

13 February 2026