Java设计模式(二)工厂设计模式

  工厂设计模式是Java最常用得设计模式之一。属于创建者模式。工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程隔离起来,达到提高灵活性的目的。具有三方面的组成:①抽象产品类角色,一般是具体产品继承的父类或接口;②具体产品角色,工厂类所创建的对象就是此角色的实例;③工厂类角色,是工厂设计模式的核心,含有一定的商业逻辑和判断逻辑,用于产生具体产品实例。 

 

1)创建一个接口Shape,有void方法。 

public interface Shape {
	void draw() ;
}

2)创建实现相同接口的具体类,Rectangel.javaSquare.javaCircle.java 

public class Rectangle implements Shape {
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Inside Rectangel::draw() method.");
	}	
}
public class Square implements Shape {
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Inside Square::draw() method.");
	}
}
public class Circle implements Shape{
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("Inside Circle::draw() method.");
	}
}

3)创建工厂根据给定得信息生成具体类得对象(ShapeFactgory.java)。

 

public class ShapeFactory {
	//use getShape method to get object of type shape 
	public Shape getShape(String shapeType){
		if (shapeType == null) {
			return null ;
		}
		if (shapeType.equalsIgnoreCase("CIRCLE")) {
			return new Circle() ;
		}
		if (shapeType.equalsIgnoreCase("Rectangle")) {
			return new Rectangle() ;
		}
		if (shapeType.equalsIgnoreCase("SQUARE")) {
			return new Square() ;
		}
		return null ;
	}
}

 

4)使用工厂通过传递类型等信息来获取具体类得对象(FactoryPatternDemo.java)。

public class FactoryPatternDemo {
	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 Circle
		shape1.draw();
		//get an object of Rectangle and call its draw method.
	    Shape shape2 = shapeFactory.getShape("RECTANGLE");
	    shape2.draw();
	    //get an object of Square and call its draw method.
	    Shape shape3 = shapeFactory.getShape("SQUARE");
	    shape3.draw();
	}
}

5)输出结果。

 

Inside Circle::draw() method.

Inside Rectangel::draw() method.

Inside Square::draw() method. 

 

posted @ 2017-10-19 16:50  落下树的汪汪狗  阅读(152)  评论(0编辑  收藏  举报