设计模式之工厂模式
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
首先,创建一个接口Shape.java
public interface Shape {
public void draw();
}
然后,创建子类Circle.java及Square.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("draw circle...");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("draw square...");
}
}
接着,创建一个工厂类ShapeFactory.java
public class ShapeFactory {
public <T> T getByClass(Class clazz) {
try {
return (T) Class.forName(clazz.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
最后,创建测试类Test.java
public class Test {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Circle circle = (Circle) shapeFactory.getShapeByClass(Circle.class);
circle.draw();
Square square = (Square) shapeFactory.getShapeByClass(Square.class);
square.draw();
}
}
另外,如果是抽象工厂的话,创建一个抽象工厂类AbstractFactory.java
public abstract class AbstractFactory {
public abstract <T> T getByClass(Class clazz);
}
然后,创建实现类AbstractShapeFactory.java
public class AbstractShapeFactory extends AbstractFactory {
@Override
public <T> T getByClass(Class clazz) {
try {
T cls = (T) Class.forName(clazz.getName()).newInstance();
return cls;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
最后,测试类Test.java
public class Test {
public static void main(String[] args) {
AbstractFactory shapeFactory = new AbstractShapeFactory();
Circle circle = (Circle) shapeFactory.getByClass(Circle.class);
circle.draw();
Square square = (Square) shapeFactory.getByClass(Square.class);
square.draw();
}
}