设计模式之(一)Factory模式
敏捷软件开发-原则、模式与实践
依赖倒置原则(DIP)说的是任何类都应依赖于抽象类,避免依赖于具体类。
Circle c = new Circle(r);
Circle是一个具体类,所以创建Circle的势力都违反了DIP。很多具体类都是
非常易变的,依赖于他们会带来问题。这就用到了Factory模式,factory模式
允许只依赖于抽象接口就能创建具体对象的实例。
下面是个具体的例子
//Client.java
package com.factory;
import static org.junit.Assert.*;
import org.junit.Test;
public class Client {
@Test
public void testFactory() {
ShapeFactory sf = new ShapeFactoryImpl();
Shape s = sf.make("Circle");
assertTrue(s instanceof Circle);
}
}
//ShapeFactory.java
package com.factory;
public interface ShapeFactory {
Shape make(String shapeName);
}
//Shape.java
package com.factory;
public abstract class Shape {
}
//Circle.java
package com.factory;
public class Circle extends Shape {
}
//ShapeFactoryImpl .java
package com.factory;
public class ShapeFactoryImpl implements ShapeFactory {
@Override
public Shape make(String shapeName) {
if(shapeName.equals("Circle")) {
return new Circle();
} else {
return null;
}
}
}