设计模式之工厂模式

工厂模式原理图

在这里插入图![工厂模式原理图](https://img-blog.csdnimg.c

工厂模式设计步骤

步骤一
创建一个接口(Shape)

package FactoryPattern;
public interface Shape {
    void draw();
}

步骤二
创建实现接口的实体类
Circle.class

   package FactoryPattern;
    public class Circle implements Shape{
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Circle");
	}
}

Square.class

package FactoryPattern;
public class Square implements Shape{
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Sahpe");
	}
}

Rectangle.class

 package FactoryPattern;
public class Rectangle implements Shape{
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Rectangle");
	}
}

步骤三
创建一个工厂,生成基于给定信息的实体类的对象。

package FactoryPattern;

public class ShapeFactory {
    public Shape getShape(String s){
    	if(s.equalsIgnoreCase("Circle"))
    		return new Circle();
    	else if(s.equalsIgnoreCase("Square"))
    		return new Square();
    	else if(s.equalsIgnoreCase("Rectangle"))
    		return new Rectangle();
    	else
    		return null;
    	
    }
}

步骤四
使用该工厂,通过传递类型信息来获取实体类的对象。

package FactoryPattern;

public class FactoryPatternDemo {
    public static void main(String[] args) {
	    ShapeFactory shapeFactory = new ShapeFactory();
	    Shape s1 = shapeFactory.getShape("circle");
	    s1.draw();
	    Shape s2 = shapeFactory.getShape("square");
	    s2.draw();
	    Shape s3 = shapeFactory.getShape("rectangle");
	    s3.draw();
	    Shape s4 = shapeFactory.getShape("angle");
	    if(s4 != null)
	        s4.draw();
    }
}

结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值