跳至主要內容

Design Patterns Factory

Section9lab...小于 1 分钟DesignPatternjava

Design Patterns Factory


一、创建型模式:

2、工厂模式

简单工厂

─model
    │  ShapeFactory.java
    │  TestDemo.java
    │
    └─shape
            Circle.java
            Rectangle.java
            Shape.java
            Square.java

public interface Shape

package com.test.cases.model.shape;

public interface Shape {
    void draw();
}

public class Square implements Shape

package com.test.cases.model.shape;

public class Square implements Shape{
    @Override
    public void draw() {
        System.out.println("Shape Square draw");
    }
}

public class Rectangle implements Shape

package com.test.cases.model.shape;

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

public class Circle implements Shape

package com.test.cases.model.shape;

public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("Shape Circle draw");
    }
}

public class ShapeFactory

package com.test.cases.model;

import com.test.cases.model.shape.Circle;
import com.test.cases.model.shape.Rectangle;
import com.test.cases.model.shape.Shape;
import com.test.cases.model.shape.Square;

public class ShapeFactory {
    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;
    }
}

public class TestDemo

package com.test.cases.model;

import com.test.cases.model.shape.Shape;

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

        //获取 Circle 的对象,并调用它的 draw 方法
        Shape circle = shapeFactory.getShape("CIRCLE");
        circle.draw();

        //获取 Rectangle 的对象,并调用它的 draw 方法
        Shape rectangle = shapeFactory.getShape("RECTANGLE");
        rectangle.draw();

        //获取 Square 的对象,并调用它的 draw 方法
        Shape square = shapeFactory.getShape("SQUARE");
        square.draw();
    }
}

抽象工厂

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.6