• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java 工厂模式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Java设计模式 - 工厂模式


工厂模式是一种创建模式,因为此模式提供了更好的方法来创建对象。

在工厂模式中,我们创建对象而不将创建逻辑暴露给客户端。

例子

在以下部分中,我们将展示如何使用工厂模式创建对象。

由工厂模式创建的对象将是形状对象,如圆形,矩形。

首先,我们设计一个接口来表示Shape。

public interface Shape {
   void draw();
}

然后我们创建实现接口的具体类。

以下代码用于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.");
   }
}

核心工厂模式是一个Factory类。以下代码显示了如何为Shape对象创建Factory类。

ShapeFactory类基于传递给getShape()方法的String值创建Shape对象。如果String值为CIRCLE,它将创建一个Circle对象。

public class ShapeFactory {
  
   //use getShape method to get object of type shape 
   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;
   }
}

以下代码具有main方法,并且它使用Factory类通过传递类型等信息来获取具体类的对象。

public class Main {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

上面的代码生成以下结果。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java 类实例发布时间:2022-01-22
下一篇:
Java 关键字发布时间:2022-01-22
热门推荐
    热门话题
    阅读排行榜

    扫描微信二维码

    查看手机版网站

    随时了解更新最新资讯

    139-2527-9053

    在线客服(服务时间 9:00~18:00)

    在线QQ客服
    地址:深圳市南山区西丽大学城创智工业园
    电邮:jeky_zhao#qq.com
    移动电话:139-2527-9053

    Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap