工厂模式是一种创建型设计模式

简介: 工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,而是通过使用一个共同的接口来指向新创建的对象。

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

下面是一个简单工厂模式的实现例子:

public interface Shape {
   
   void draw();
}

public class Rectangle implements Shape {
   
   public void draw() {
   
      System.out.println("Inside Rectangle::draw() method.");
   }
}

public class Square implements Shape {
   
   public void draw() {
   
      System.out.println("Inside Square::draw() method.");
   }
}

public class ShapeFactory {
   
   // Using static method to instantiate the objects
   public static 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;
   }
}
相关文章
|
3天前
|
设计模式 搜索推荐 数据库连接
第二篇 创建型设计模式 - 灵活、解耦的创建机制
第二篇 创建型设计模式 - 灵活、解耦的创建机制
|
4天前
|
设计模式 JavaScript 前端开发
[设计模式Java实现附plantuml源码~创建型] 复杂对象的组装与创建——建造者模式
[设计模式Java实现附plantuml源码~创建型] 复杂对象的组装与创建——建造者模式
|
4天前
|
设计模式 Java Go
[设计模式Java实现附plantuml源码~创建型] 对象的克隆~原型模式
[设计模式Java实现附plantuml源码~创建型] 对象的克隆~原型模式
|
4天前
|
设计模式 Java Go
[设计模式Java实现附plantuml源码~创建型] 产品族的创建——抽象工厂模式
[设计模式Java实现附plantuml源码~创建型] 产品族的创建——抽象工厂模式
|
4天前
|
设计模式 存储 JavaScript
[设计模式Java实现附plantuml源码~创建型] 多态工厂的实现——工厂方法模式
[设计模式Java实现附plantuml源码~创建型] 多态工厂的实现——工厂方法模式
|
4天前
|
设计模式 Java Go
[设计模式Java实现附plantuml源码~创建型] 集中式工厂的实现~简单工厂模式
[设计模式Java实现附plantuml源码~创建型] 集中式工厂的实现~简单工厂模式
|
4天前
|
设计模式 安全 Java
[设计模式Java实现附plantuml源码~创建型] 确保对象的唯一性~单例模式
[设计模式Java实现附plantuml源码~创建型] 确保对象的唯一性~单例模式
|
4天前
|
设计模式 测试技术 Go
[设计模式 Go实现] 创建型~ 原型模式
[设计模式 Go实现] 创建型~ 原型模式
|
4天前
|
设计模式 测试技术 Go
[设计模式 Go实现] 创建型~工厂方法模式
[设计模式 Go实现] 创建型~工厂方法模式
|
4天前
|
设计模式 测试技术 Go
[设计模式 Go实现] 创建型~建造者模式
[设计模式 Go实现] 创建型~建造者模式