设计模式之------工厂模式

工厂模式简介内容参考易百教程

1、创建接口
2、创建实现接口的具体类,实现接口并重写接口中的方法。(对于抽象类,可以不用实现接口中的所有方法,可以又他的子类实现。普通的实现类,必须实现接口中的所有方法。)
3、创建工厂类
4、创建演示类,通过工厂类获取对象

流程如下:演示类中初始化工厂类,通过工厂类创建对象,对象实现了接口中的方法。
在这里插入图片描述

1、创建Shape接口
Shape.java

public interface Shape {
    void draw();
}

2.创建实现接口的具体类
Rectangle.java

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

Square.java

public class Square implements Shape {

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

Circle.java

public class Circle implements Shape {

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

3、创建工厂类
ShapeFactory.java

public class ShapeFactory {

    public Shape getShape(String shapetype){

        if(shapetype == null){
            System.out.println("shape type is null");
            return null;
        }
        
        if(shapetype.equalsIgnoreCase("Rectangle")){
            System.out.println("Rectangle   ---  is shape type");
            return  new Rectangle();
        }else if (shapetype.equalsIgnoreCase("Square")){
            System.out.println("Square  ---------  is shape type");
            return new Square();
        }else if(shapetype.equalsIgnoreCase("Circle")){
            System.out.println("Circle  is --- shape type");
            return new Circle();
        }else {
            System.out.println("not found this method");
        }
        return  null;
    }
}

4、创建创建演示类,通过工厂类创建对象
FactoryPatternDemo.java

public class FactoryPatternDemo {
    
    public static void main(String[] args) {

        ShapeFactory shapeFactory = new ShapeFactory();

        Shape shape1 = shapeFactory.getShape("Rectangle");
        shape1.draw();

        System.out.println("1-------------------------------2");

        Shape shape2 = shapeFactory.getShape("Circle");
        shape2.draw();

        System.out.println("2-------------------------------2");

        Shape shape3 = shapeFactory.getShape("Square");
        shape3.draw();

    }
}

结果如下:

Rectangle   ---  is shape type
Rectangle --- implements Shape1-------------------------------2
Circle  is --- shape type
Circle --- implements Shape2-------------------------------2
Square  ---------  is shape type
Square --- implements Shape
Process finished with exit code 0

参考链接:Java工厂设计模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值