• 抽象工厂模式 rust和java的实现


    抽象工厂模式

    抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。

    在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

    抽象工厂模式提供了一种创建一系列相关或相互依赖对象的接口,而无需指定具体实现类。通过使用抽象工厂模式,可以将客户端与具体产品的创建过程解耦,使得客户端可以通过工厂接口来创建一族产品。

    介绍

    意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

    主要解决:主要解决接口选择的问题。

    何时使用:系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。

    如何解决:在一个产品族里面,定义多个产品。

    关键代码:在一个工厂里聚合多个同类产品。

    应用实例:工作了,为了参加一些聚会,肯定有两套或多套衣服吧,比如说有商务装(成套,一系列具体产品)、时尚装(成套,一系列具体产品),甚至对于一个家庭来说,可能有商务女装、商务男装、时尚女装、时尚男装,这些也都是成套的,即一系列具体产品。假设一种情况(现实中是不存在的,但有利于说明抽象工厂模式),在您的家中,某一个衣柜(具体工厂)只能存放某一种这样的衣服(成套,一系列具体产品),每次拿这种成套的衣服时也自然要从这个衣柜中取出了。用 OOP 的思想去理解,所有的衣柜(具体工厂)都是衣柜类的(抽象工厂)某一个,而每一件成套的衣服又包括具体的上衣(某一具体产品),裤子(某一具体产品),这些具体的上衣其实也都是上衣(抽象产品),具体的裤子也都是裤子(另一个抽象产品)。

    优点:当一个产品族中的多个对象被设计成一起工作时,它能保证客户端始终只使用同一个产品族中的对象。

    缺点:产品族扩展非常困难,要增加一个系列的某一产品,既要在抽象的 Creator 里加代码,又要在具体的里面加代码。

    使用场景: 1、皮肤系统,一整套一起换。

    抽象工厂模式包含以下几个核心角色:

    抽象工厂(Abstract Factory):声明了一组用于创建产品对象的方法,每个方法对应一种产品类型。抽象工厂可以是接口或抽象类。
    具体工厂(Concrete Factory):实现了抽象工厂接口,负责创建具体产品对象的实例。
    抽象产品(Abstract Product):定义了一组产品对象的共同接口或抽象类,描述了产品对象的公共方法。
    具体产品(Concrete Product):实现了抽象产品接口,定义了具体产品的特定行为和属性。
    抽象工厂模式通常涉及一族相关的产品,每个具体工厂类负责创建该族中的具体产品。客户端通过使用抽象工厂接口来创建产品对象,而不需要直接使用具体产品的实现类。

    实现架构图

    我们将创建 Shape 和 Color 接口和实现这些接口的实体类。下一步是创建抽象工厂类 AbstractFactory。接着定义工厂类 ShapeFactory 和 ColorFactory,这两个工厂类都是扩展了 AbstractFactory。然后创建一个工厂创造器/生成器类 FactoryProducer。

    AbstractFactoryPatternDemo 类使用 FactoryProducer 来获取 AbstractFactory 对象。它将向 AbstractFactory 传递形状信息 Shape(CIRCLE / RECTANGLE / SQUARE),以便获取它所需对象的类型。同时它还向 AbstractFactory 传递颜色信息 Color(RED / GREEN / BLUE),以便获取它所需对象的类型。

    抽象工厂模式的 UML 图

    java实现

    步骤 1
    为形状创建一个接口。

    Shape.java
    public interface Shape {
       void draw();
    }
    
    • 1
    • 2
    • 3
    • 4

    请添加图片描述

    步骤 2
    创建实现接口的实体类。

    Rectangle.java
    
    Rectangle.java
    public class Rectangle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Rectangle::draw() method.");
       }
    }
    Square.java
    public class Square implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Square::draw() method.");
       }
    }
    Circle.java
    public class Circle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Circle::draw() method.");
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    步骤 3
    为颜色创建一个接口。

    Color.java
    public interface Color {
       void fill();
    }
    
    • 1
    • 2
    • 3
    • 4

    步骤4
    创建实现接口的实体类。

    Red.java
    public class Red implements Color {
     
       @Override
       public void fill() {
          System.out.println("Inside Red::fill() method.");
       }
    }
    Green.java
    public class Green implements Color {
     
       @Override
       public void fill() {
          System.out.println("Inside Green::fill() method.");
       }
    }
    Blue.java
    public class Blue implements Color {
     
       @Override
       public void fill() {
          System.out.println("Inside Blue::fill() method.");
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    步骤 5
    为 Color 和 Shape 对象创建抽象类来获取工厂。

    AbstractFactory.java
    public abstract class AbstractFactory {
       public abstract Color getColor(String color);
       public abstract Shape getShape(String shape);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    步骤 6
    创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象。

    
    ShapeFactory.java
    public class ShapeFactory extends AbstractFactory {
        
       @Override
       public Shape getShape(String shapeType){
          if(shapeType == null){
             return null;
          }        
          if(shapeType.equalsIgnoreCase("CIRCLE")){
             return new Circle();
          } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
             return new Rectangle();
          } else if(shapeType.equalsIgnoreCase("SQUARE")){
             return new Square();
          }
          return null;
       }
       
       @Override
       public Color getColor(String color) {
          return null;
       }
    }
    ColorFactory.java
    public class ColorFactory extends AbstractFactory {
        
       @Override
       public Shape getShape(String shapeType){
          return null;
       }
       
       @Override
       public Color getColor(String color) {
          if(color == null){
             return null;
          }        
          if(color.equalsIgnoreCase("RED")){
             return new Red();
          } else if(color.equalsIgnoreCase("GREEN")){
             return new Green();
          } else if(color.equalsIgnoreCase("BLUE")){
             return new Blue();
          }
          return null;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    步骤 7
    创建一个工厂创造器/生成器类,通过传递形状或颜色信息来获取工厂。

    FactoryProducer.java
    public class FactoryProducer {
       public static AbstractFactory getFactory(String choice){
          if(choice.equalsIgnoreCase("SHAPE")){
             return new ShapeFactory();
          } else if(choice.equalsIgnoreCase("COLOR")){
             return new ColorFactory();
          }
          return null;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    步骤 8
    使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象。

    AbstractFactoryPatternDemo.java
    public class AbstractFactoryPatternDemo {
       public static void main(String[] args) {
     
          //获取形状工厂
          AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
     
          //获取形状为 Circle 的对象
          Shape shape1 = shapeFactory.getShape("CIRCLE");
     
          //调用 Circle 的 draw 方法
          shape1.draw();
     
          //获取形状为 Rectangle 的对象
          Shape shape2 = shapeFactory.getShape("RECTANGLE");
     
          //调用 Rectangle 的 draw 方法
          shape2.draw();
          
          //获取形状为 Square 的对象
          Shape shape3 = shapeFactory.getShape("SQUARE");
     
          //调用 Square 的 draw 方法
          shape3.draw();
     
          //获取颜色工厂
          AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
     
          //获取颜色为 Red 的对象
          Color color1 = colorFactory.getColor("RED");
     
          //调用 Red 的 fill 方法
          color1.fill();
     
          //获取颜色为 Green 的对象
          Color color2 = colorFactory.getColor("GREEN");
     
          //调用 Green 的 fill 方法
          color2.fill();
     
          //获取颜色为 Blue 的对象
          Color color3 = colorFactory.getColor("BLUE");
     
          //调用 Blue 的 fill 方法
          color3.fill();
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    步骤 9
    执行程序,输出结果:

    Inside Circle::draw() method.
    Inside Rectangle::draw() method.
    Inside Square::draw() method.
    Inside Red::fill() method.
    Inside Green::fill() method.
    Inside Blue::fill() method.
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    rust实现

    由于设计思想是一致的,关于rust的实现就不再赘述上述的步骤,直接贴上完整的代码。

    // 定义接口
    
    // 创建实体类
    struct Rectangle;
    struct Square;
    struct  Circle;
    struct ShapeFactory ;
    struct ColorFactory ;
    struct  FactoryProducer ;
    struct Red;
    struct Blue;
    struct  Green;
    pub trait Color{
        fn fill(&self);  
    }
    impl Color for Red {
        fn fill(&self) {
            println!("Inside Red::fill() method.");
        }
    }
    impl Color for Blue {
        fn fill(&self) {
            println!("Inside Blue::fill() method.");
        }
    }
    impl Color for Green {
        fn fill(&self) {
            println!("Inside Green::fill() method.");
        }
    }
    
    
    pub  trait Shape {
        fn draw(&self);  
    }
    impl Shape for Rectangle {
        fn draw(&self) {
            println!("Inside Rectangle::draw() method.");
        }
    }
    impl Shape for Square {
        fn draw(&self) {
            println!("Inside Square::draw() method.");
        }
    }
    impl Shape for Circle {
        fn draw(&self) {
            println!("Inside Circle::draw() method.");
        }
    }
    pub trait AbstractFactory {
        fn get_color(&self,color: &str)->Result<Box<dyn Color>>;
        fn get_shape(&self,shape: &str)->Box<dyn Shape>;
     }
    
    impl AbstractFactory for ShapeFactory {
        fn get_shape(&self,shape_type: &str)->Box<dyn Shape>{
            if shape_type=="CIRCLE" {
                Box::new(Circle{})
            }else if shape_type=="RECTANGLE" {
                Box::new(Rectangle{})
            }else if  shape_type=="SQUARE"{
                Box::new(Square{})
            }else {
                panic!("输入的类型不存在");
            }
      
        }
        fn get_color(&self,_shape_type: &str)->Box<dyn Color>{
    
            panic!("输入的类型不存在");
      
        }
    }
    impl AbstractFactory for ColorFactory {
        fn get_color(&self,shape_type: &str)->Box<dyn Color>{
            if shape_type=="RED" {
                Box::new(Red{})
            }else if shape_type=="BLUE" {
                Box::new(Blue{})
            }else if  shape_type=="GREEN"{
                Box::new(Green{})
            }else {
                panic!("输入的类型不存在");
            }
        }
        fn get_shape(&self,_shape_type: &str)->Box<dyn Shape>{
    
            panic!("输入的类型不存在");
        }
    
    }
    
    impl  FactoryProducer {
        fn get_factory(choice: &str)-> Box<dyn AbstractFactory>{
            if choice=="COLOR" {
                Box::new(ColorFactory{})
            }else if choice=="SHAPE" {
                Box::new(ShapeFactory{})
            }else {
                panic!("输入的类型不存在");
            }
        }
    }
    
    fn main() {
        let shape=FactoryProducer::get_factory("SHAPE");
        let shape1=shape.get_shape("CIRCLE");
        shape1.draw();
        let shape2=shape.get_shape("RECTANGLE");
        shape2.draw();
        let shape3=shape.get_shape("SQUARE");
        shape3.draw();
        let color=FactoryProducer::get_factory("COLOR");
        let color1=color.get_color("RED");
        color1.fill();
        let color2=color.get_color("BLUE");
        color2.fill();
        let color3=color.get_color("GREEN");
        color3.fill();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121

    rust代码仓库

    https://github.com/onenewcode/design.git
    本教程项目在bin文件夹下的abstractfactory.rs文件中

  • 相关阅读:
    简单记录一下在java的Mybatis-plus中用一个SQL语句查询一个嵌套的实体类(实体类中有List,List中还有List)
    .NET面试宝典130道经典面试真题及答案
    上传文件到七牛云并限制并发数量
    PostgreSQL之数据类型及开发技巧
    基于Python实现看图说话和微表情识别
    【学习笔记】Python+request+Unittest接口测试入门
    『德不孤』Pytest框架 — 12、Pytest中Fixture装饰器(二)
    MIT课程分布式系统学习06——Fault Tolerance raft1
    springboot接口参数校验(有这一篇就够了)
    React 全栈体系(七)
  • 原文地址:https://blog.csdn.net/studycodeday/article/details/134248937