Java实现(01)——工厂模式(Factory Pattern)

  在Java中工厂模式是最常用的模式之一,提供了一种非常好的创建对象的的方法,因此可以将这种模式归类于创建型模式。在工厂模式中,用户可以很容易地创建对象而不需要知道内在的逻辑,可以使用通用的接口引用创建的对象。

  本例中创建一个Shape类型的接口,和Cricle, Square, Rectangle实现的类,创建一个ShapeFactory工厂类,示例通过向ShapeFactory中传递(CIRCLE/RECTANGLE/SQUARE)调用ShapeFactory获得相应的Shape对象。

创建一个Shape类型的接口

public interface Shape {
    public void draw();
}
创建三个实现该接口的类

public class Rectangle implements Shape{
    @Override
    public void draw() {
        System.out.println("Inside Ractangle::draw() method.");
    }
}
public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
public class Square implements Shape{
    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}
创建工厂类

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 FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        shape1.draw();
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        shape2.draw();
        Shape shape3 = shapeFactory.getShape("SQUARE");
        shape3.draw();
    }
}
输出:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值