Java的原廠模式簡介,Java原廠模式簡介

來源:互聯網
上載者:User

Java的原廠模式簡介,Java原廠模式簡介

原廠模式主要是為建立對象提供過渡介面,以便將建立對象的具體過程屏蔽隔離起來,達到提高靈活性的目的。

在下面的章節中,我們將展示如何使用原廠模式來建立對象。

由原廠模式建立的對象將是形狀的物體,如圓形,矩形。

首先,我們設計代表形狀的介面。

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 Rectangle implements Shape {   @Override   public void draw() {      System.out.println("Inside Rectangle::draw() method.");   }}

 

Circle.java

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

 

核心原廠模式是工廠類。下面的代碼示範如何建立一個工廠類Shape對象。

該ShapeFactory類建立基於傳遞到getShape()方法的字串值Shape對象。如果字串值是圓,它會建立一個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;   }}

 

下面的代碼有mian方法,它採用工廠類傳遞一個資訊,如類型,以獲得具體類的對象。

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();   }}

 

原文地址:http://www.manongjc.com/article/135.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.