设计模式

2022/4/25 23:15:40

本文主要是介绍设计模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、简介

设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。

使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。

1、工厂模式

属于创建型模式,它提供了一种创建对象的最佳方式。在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

步骤1:创建一个接口

public interface Shape {
   void draw();
}

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

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

步骤3:创建一个工厂,生成基于给定信息的实体类的对象

 1 public class ShapeFactory {
 2     
 3    //使用 getShape 方法获取形状类型的对象
 4    public Shape getShape(String shapeType){
 5       if(shapeType == null){
 6          return null;
 7       }        
 8       if(shapeType.equalsIgnoreCase("CIRCLE")){
 9          return new Circle();
10       } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
11          return new Rectangle();
12       } else if(shapeType.equalsIgnoreCase("SQUARE")){
13          return new Square();
14       }
15       return null;
16    }
17 }

步骤4:使用该工厂,通过传递类型信息来获取实体类的对象。

 1 public class FactoryPatternDemo {
 2  
 3    public static void main(String[] args) {
 4       ShapeFactory shapeFactory = new ShapeFactory();
 5  
 6       //获取 Circle 的对象,并调用它的 draw 方法
 7       Shape shape1 = shapeFactory.getShape("CIRCLE");
 8  
 9       //调用 Circle 的 draw 方法
10       shape1.draw();
11  
12       //获取 Rectangle 的对象,并调用它的 draw 方法
13       Shape shape2 = shapeFactory.getShape("RECTANGLE");
14  
15       //调用 Rectangle 的 draw 方法
16       shape2.draw();
17  
18       //获取 Square 的对象,并调用它的 draw 方法
19       Shape shape3 = shapeFactory.getShape("SQUARE");
20  
21       //调用 Square 的 draw 方法
22       shape3.draw();
23    }
24 }

 



这篇关于设计模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程