1.接口:Shape
2.接口实现类:Rectangle、Circle
3.工厂:ShapeFactory:作为媒婆,为它们连线搭桥,看上哪个,通过媒婆实例化哪个
4.Main方法运行
作为新手,说了一大堆理论,也可能不懂,
不如先看代码:
一、一个接口:形状Shape, 有个draw()方法
package Factory;
/*
* 接口:形状
*/
public interface Shape {
void draw();
}
二、两个接口实现类:三角形 Rectangle、圆形 Circle
1、Rectangle
package Factory;
/*
* 接口实现类:三角形
*/
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Rectangle::draw() method.");
}
}
2、Circle
package Factory;
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw() method.");
}
}
三、工厂:ShapeFactory
通过工厂来选择实例化三角形Rectangle,还是圆形Circle
package Factory;
/*
* 通过工厂来选择实例化三角形Rectangle,还是圆形Circle
*/
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();
}
return null;
}
}
四、Main方法
package Factory;
/*
* Main方法
*/
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();
}
}
运行一下,看看效果,好好体会一下!
当然,也可以不要第三步,在第四步的Main方法里直接实例化接口的实现类,修改如下:
package Factory;
/*
* Main方法
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
Shape shape1 = new Rectangle();
shape1.draw();
Shape shape2 = new Circle();
shape2.draw();
}
}