
在 Ruby 中实现简单工厂模式和工厂方法模式是面向对象编程中常见的实践。以下将详细阐述这两种设计模式的实现方式,并通过具体的代码示例进行说明。
1. 简单工厂模式(Simple Factory Pattern)
简单工厂模式是一种创建型设计模式,它通过一个工厂类来封装对象的创建逻辑。工厂类根据输入参数决定创建哪种类型的对象。这种模式的优点是将对象的创建逻辑集中在一个工厂类中,便于管理和扩展。
示例代码
假设我们有一个场景,需要根据用户输入创建不同类型的动物对象(如猫、狗等),并让它们发出声音。
# 定义动物的基类
class Animal
def speak
raise NotImplementedError, "You should implement the speak method"
end
end
# 定义具体的动物类
class Dog < Animal
def speak
"Woof!"
end
end
class Cat < Animal
def speak
"Meow!"
end
end
# 定义简单工厂类
class AnimalFactory
def self.create_animal(type)
case type
when :dog
Dog.new
when :cat
Cat.new
else
raise ArgumentError, "Unknown animal type: #{type}"
end
end
end
# 使用简单工厂模式创建对象
animal = AnimalFactory.create_animal(:dog)
puts animal.speak # 输出: Woof!
animal = AnimalFactory.create_animal(:cat)
puts animal.speak # 输出: Meow!
分析
- AnimalFactory 是一个简单的工厂类,它通过
create_animal方法根据传入的类型参数创建具体的动物对象。 - 这种模式将对象的创建逻辑封装在工厂类中,客户端代码无需直接调用具体的类构造方法,从而降低了耦合度。
2. 工厂方法模式(Factory Method Pattern)
工厂方法模式是一种更为灵活的创建型设计模式。它定义了一个创建对象的接口,但将具体的创建逻辑交给子类实现。这种方式使得工厂类可以延迟到子类中实现具体的对象创建。
示例代码
假设我们有一个场景,需要根据不同的操作系统创建对应的文件系统对象(如 Windows 文件系统、Linux 文件系统等)。
# 定义文件系统的基类
class FileSystem
def create_file
raise NotImplementedError, "You should implement the create_file method"
end
end
# 定义具体的文件系统类
class WindowsFileSystem < FileSystem
def create_file
"Creating a file on Windows"
end
end
class LinuxFileSystem < FileSystem
def create_file
"Creating a file on Linux"
end
end
# 定义工厂基类
class FileSystemFactory
def create_file_system
raise NotImplementedError, "You should implement the create_file_system method"
end
end
# 定义具体的工厂类
class WindowsFileSystemFactory < FileSystemFactory
def create_file_system
WindowsFileSystem.new
end
end
class LinuxFileSystemFactory < FileSystemFactory
def create_file_system
LinuxFileSystem.new
end
end
# 使用工厂方法模式创建对象
windows_factory = WindowsFileSystemFactory.new
windows_file_system = windows_factory.create_file_system
puts windows_file_system.create_file # 输出: Creating a file on Windows
linux_factory = LinuxFileSystemFactory.new
linux_file_system = linux_factory.create_file_system
puts linux_file_system.create_file # 输出: Creating a file on Linux
分析
- FileSystemFactory 是一个工厂基类,定义了
create_file_system方法,但具体的实现由子类完成。 - WindowsFileSystemFactory 和 LinuxFileSystemFactory 是具体的工厂类,分别实现了创建 Windows 文件系统和 Linux 文件系统的逻辑。
- 这种模式使得工厂类可以根据不同的需求扩展,而无需修改客户端代码,符合开闭原则。
总结
- 简单工厂模式通过一个工厂类集中管理对象的创建逻辑,适合简单的场景,但扩展性有限。
- 工厂方法模式通过定义工厂接口,将具体的创建逻辑延迟到子类中实现,具有更好的扩展性和灵活性。
如果你需要进一步的代码优化或对其他设计模式的解释,请随时告知。
更多技术文章见公众号: 大城市小农民

848

被折叠的 条评论
为什么被折叠?



