
工厂模式的代码实现
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
本段介绍如何在编程中通过创建抽象类或接口来定义产品类型,并设计具体工厂类来实例化这些产品的过程,详细探讨了工厂方法模式的代码实现及其应用场景。
简单工厂模式是一种设计模式,在这种模式下创建对象的类被称为“工厂”,它可以决定应该实例化哪一个产品类,并返回一个产品的实例。
工厂方法模式定义了一个用于创建对象的接口,但由子类决定要实例化的类是哪个。使用配置文件来指定具体工厂类的名字,它可以根据不同的业务需求选择具体的实现方式。
抽象工厂模式提供了一种方法来访问一组相关或依赖的对象而无需指定它们的具体类。在该模式中定义一个框架,创建一系列相关的对象而不必明确地指定他们的类型。
以下是对这三种设计模式的示例代码:
简单工厂:
```python
class OperationFactory:
@staticmethod
def create_operation(operate):
if operate == +:
return Add()
elif operate == -:
return Subtraction()
# 使用方式:
operation = OperationFactory.create_operation(+)
```
工厂方法:
```java
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() { System.out.println(Inside Rectangle::draw() method.); }
}
// Client code uses Factory Method to create objects of concrete classes.
public class AbstractFactoryDemo {
private static abstract class ShapeFactory {
public abstract Shape getShape(String shapeType);
}
// Concrete factory implementing the factory method
private static class RectangleFactory extends ShapeFactory {
@Override
public Shape getShape(String shapeType) { return new Rectangle(); }
}
}
```
抽象工厂:
```java
interface AbstractFactory {
Color getColor();
}
class Red implements Color{
@Override
public void fill() { System.out.println(Inside Red::fill() method.); }
}
// Client code uses Factory Method to create objects of concrete classes.
public class AbstractFactoryDemo {
private static abstract class ShapeFactory {
public abstract Shape getShape(String shapeType);
}
// Concrete factory implementing the factory method
private static class RectangleFactory extends ShapeFactory {
@Override
public Shape getShape(String shapeType) { return new Rectangle(); }
}
}
```
以上就是简单工厂模式、工厂方法模式和抽象工厂模式的示例代码。
全部评论 (0)


