import factoryPattern.factoryMethod.service.Shape;
/*
* 创建接口,同种产品的不同系列分别实现该工厂接口(比如三角形、矩形、椭圆均同 为形状产品)。
* 消费产品系列时只需调用该系列的工厂方法生产产品就可以了,这样避免了简单工厂方法的缺点:
* 一旦该工厂方法出现故障,其他产品受到影响
*/
public interface ShapeFactory {
public Shape getShape();
}
public class CircleFactory implements ShapeFactory{
@Override
public Shape getShape() {
return new Circle();
}
}
public class RectangleFactory implements ShapeFactory{
@Override
public Shape getShape() {
return new Rectangle();
}
}
public class SquareFactory implements ShapeFactory{
@Override
public Shape getShape() {
return new Square();
}
}
public interface Shape {
String draw();
}
public class Circle implements Shape{
@Override
public String draw() {
return "Circle draw";
}
}
public class Rectangle implements Shape {
@Override
public String draw() {
return "Rectangle draw";
}
}
public class Square implements Shape{
@Override
public String draw() {
return "Square draw";
}
}
public class ShapeFactoryTest {
@Test
public void testShapeFactory(){
ShapeFactory circleFactory=new CircleFactory();
ShapeFactory squareFactory=new SquareFactory();
Shape circle=circleFactory.getShape();
Shape square=squareFactory.getShape();
assertEquals("Circle draw",circle.draw());
assertEquals("Square draw",square.draw());
}
}