Java工厂设计模式

来源:互联网 发布:linux 用户提权 编辑:程序博客网 时间:2024/05/19 21:04

工厂模式是Java中最常用的设计模式之一。 这种类型的设计模式属于创建模式,因为此模式提供了创建对象的最佳方法之一。

在工厂模式中,我们没有创建逻辑暴露给客户端创建对象,并使用一个通用的接口引用新创建的对象。

我们将创建一个Shape接口和实现Shape接口的具体类。 一个工厂类ShapeFactory会在下一步中定义。

FactoryPatternDemo这是一个演示类,将使用ShapeFactory来获取一个Shape对象。 它会将信息(CIRCLE/RECTANGLE/SQUARE)传递给ShapeFactory以获取所需的对象类型。

下面是FactoryPattern Java Code

package com.milo.patterns;/** * <b>工厂模式是Java中最常用的设计模式之一。 这种类型的设计模式属于创建模式, * 因为此模式提供了创建对象的最佳方法之一。在工厂模式中,我们没有创建逻辑暴露给客户端创建对象, * 并使用一个通用的接口引用新创建的对象。</b><br> * *  step 1:创建一个接口 * @author MILO * */interface Shape {void draw();}/** * step 2:创建实现相同接口的具体类。如下所示几个类 *  * @author MILO * */class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Inside Rectangle::draw() method.");}}class Square implements Shape {@Overridepublic void draw() {System.out.println("Inside Square::draw() method.");}}class Circle implements Shape {@Overridepublic void draw() {System.out.println("Inside Circle::draw() method.");}}/** * step 3:创建工厂根据给定的信息生成具体类的对象。 *  * @author MILO * */public class ShapeFactory {// use getShape method to get object of type shapepublic 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;}/** * step 4:使用工厂通过传递类型等信息来获取具体类的对象。 *  * @param args */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 Circleshape1.draw();// get an object of Rectangle and call its draw method.Shape shape2 = shapeFactory.getShape("RECTANGLE");// call draw method of Rectangleshape2.draw();// get an object of Square and call its draw method.Shape shape3 = shapeFactory.getShape("SQUARE");// call draw method of circleshape3.draw();}}

验证输出结果如下:

Inside Circle::draw() method.Inside Rectangle::draw() method.Inside Square::draw() method.






摘录于--------《易百教程》