轻松学习设计模式1

参考:https://www.runoob.com/design-pattern/design-pattern-intro.html

 

目录

 

一、前言

二、设计模式六大原则

三、模式分类

四、创建型模式解析

1、工厂模式

2、抽象工厂模式

3、单例模式

4、建造者模式

5、原型模式

五、总结


一、前言

最近重看设计模式感触良多,做软件还是需要多看设计模式的,好处多多。

二、设计模式六大原则

1.开闭原则(Open Close Principle)
开闭原则就是说对扩展开放,对修改关闭。在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。所以一句话概括就是:为了使程序的扩展性好,易于维护和升级。想要达到这样的效果,我们需要使用接口和抽象类。

2.里氏代换原则(Liskov Substitution Principle)
里氏代换原则(Liskov Substitution Principle LSP)面向对象设计的基本原则之一。 里氏代换原则中说,任何基类可以出现的地方,子类一定可以出现。 LSP是继承复用的基石,只有当衍生类可以替换掉基类,软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。里氏代换原则是对“开-闭”原则的补充。实现“开-闭”原则的关键步骤就是抽象化。而基类与子类的继承关系就是抽象化的具体实现,所以里氏代换原则是对实现抽象化的具体步骤的规范。 

3.依赖倒转原则(Dependence Inversion Principle)
这个是开闭原则的基础,具体内容:真对接口编程,依赖于抽象而不依赖于具体。
 

4.接口隔离原则(Interface Segregation Principle)
这个原则的意思是:使用多个隔离的接口,比使用单个接口要好。还是一个降低类之间的耦合度的意思,从这儿我们看出,其实设计模式就是一个软件的设计思想,从大型软件架构出发,为了升级和维护方便。所以上文中多次出现:降低依赖,降低耦合。
 

5.迪米特法则(最少知道原则)(Demeter Principle)
为什么叫最少知道原则,就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。

6.合成复用原则(Composite Reuse Principle)
原则是尽量使用合成/聚合的方式,而不是使用继承。

三、模式分类

创建型:单例模式、工厂模式、抽象工厂模式、建造者模式、原型模式;
结构型:代理模式、适配器模式、装饰器模式、桥接模式、组合模式、享元模式、外观模式;
行为型:观察者模式、模板方法模式、命令模式、状态模式、职责链模式、解释器模式 、中介者模式、访问者模式、策略模式、备忘录模式、迭代器模式;

J2EE 模式:MVC 模式(MVC Pattern)、业务代表模式(Business Delegate Pattern)、组合实体模式(Composite Entity Pattern)、数据访问对象模式(Data Access Object Pattern)、前端控制器模式(Front Controller Pattern)、拦截过滤器模式(Intercepting Filter Pattern)、服务定位器模式(Service Locator Pattern)、传输对象模式(Transfer Object Pattern)。

四、创建型模式解析

1、工厂模式

工厂模式(Factory Pattern)提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。


int main() 
{
      ShapeFactory shapeFactory = new ShapeFactory();
      //获取 Circle 的对象,并调用它的 draw 方法
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      //调用 Circle 的 draw 方法
      shape1.draw();
      //获取 Rectangle 的对象,并调用它的 draw 方法
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      //调用 Rectangle 的 draw 方法
      shape2.draw();
      //获取 Square 的对象,并调用它的 draw 方法
      Shape shape3 = shapeFactory.getShape("SQUARE");
      //调用 Square 的 draw 方法
      shape3.draw();
   }

从调用代码中可以发现,我们只是shapeFactory工厂类以及Shape这个抽象类打交道,而没有和具体的实现打交道。如果需要椭圆绘制,需要添加新的椭圆类来实现绘制椭圆的功能。

2、抽象工厂模式

       抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

int  main() 
{
 
      //获取形状工厂
      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();
}

从调用代码我们看到,我们会和超级工厂FactoryProducer打交道,超级工厂FactoryProducer它会生产工厂,在这里它生成了shapeFactory和colorFactory。工厂生成出来之后,剩下来的事情基本和简单工厂模式一样了。

3、单例模式

      单例模式(Singleton Pattern)是最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。


//单线程版本
class SingleObject {
 

   //让构造函数为 private,这样该类就不会被实例化
   private :
      SingleObject(){}
 
   //获取唯一可用的对象
   public :
       static SingleObject & getInstance()
       {
          
         if(instance==NULL)
         {
             instance=new SingleObject()
         }
         
          return *instance;
       }
 

       void showMessage()
       {
          System.out.println("Hello World!");
       }

   //创建 SingleObject 的一个对象
   private:
      static SingleObject *instance = NULL;
 
}


//多线程版本 双重锁定效率高
class SingleObject {
 

   //让构造函数为 private,这样该类就不会被实例化
   private :
      SingleObject(){}
 
   //获取唯一可用的对象
   public :
       static SingleObject & getInstance()
       {
          
         if(instance==NULL)
         {
             {
               std::lock locker(mtx);
               if(instance==NULL)
                  instance=new SingleObject()
             }
         }
         
          return *instance;
       }
 

       void showMessage()
       {
          System.out.println("Hello World!");
       }

   //创建 SingleObject 的一个对象
   private:
      static SingleObject *instance = NULL;
      static std::mutex mtx;
 
}


int main() 
{
 

 
      //获取唯一可用的对象
      SingleObject object = SingleObject.getInstance();
 
      //显示消息
      object.showMessage();
 }

从调用代码可以发现我们只和SingleObject这个类打交道,SingleObject的getInstance返回该类的唯一实例。

4、建造者模式

    建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。

class MealBuilde
 {
 
   public:
      Meal prepareVegMeal ()
    {
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
     }   
 
     Meal prepareNonVegMeal ()
    {
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
    }
}
int main()
 {
      MealBuilder mealBuilder = new MealBuilder();
 
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());
 
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   
}

 从调用代码可以发现,我们只和mealBuilder和Meal打交道。mealBuilder负责创建meal,meal中会有一些item比如Coke和Vegburger。可以发现是一种非常简单的一种模式。

5、原型模式

     原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

class ShapeCache
 {
    

 
   public :
     static Shape getShape(String shapeId)
    {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
    }
 
   // 对每种形状都运行数据库查询,并创建该形状
   // shapeMap.put(shapeKey, shape);
   // 例如,我们要添加三种形状
    static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);
 
      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);
 
      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
    }

   private :
    static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
}


int  main() 
{
      ShapeCache.loadCache();
 
      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());        
 
      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());        
 
      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());        
 }

      从调用代码可以发现,我们会和ShapeCache和Shape打交道,ShapeCache中存储了一些原型对象,需要的时候直接从ShapeCache中克隆出原型对象。

五、总结

    设计模式中创建型模式学习还是比较简单的,难的是如何在合适的场景中使用这些模式,从而达到软件的维护复用及扩展性强。

猜你喜欢

转载自blog.csdn.net/kupe87826/article/details/108291531