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