1. 创建一个接口
public interface Shape {
void draw();
}
2. 创建接口的实现类
public class Circle implements Shape {
@Override
public void draw() {
//todo
}
}
public class Square implements Shape {
@Override
public void draw() {
//todo
}
}
3. 创建工厂
public class ShapeFactory {
public Shape getShape(String type) {
if (shape == null || "".equals(type)) {
return null;
}
if ("circle".equalsIgnoreCase()) {
return new Circle();
}
if ("square".equalsIgnoreCase()) {
return new Square();
}
return null;
}
}
4. 使用
public static void main (String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape1 = factory.getShape("circle");
shape1.fraw();
Shape shape2 = factory.getShape("circle");
shape2.fraw();
}
工厂模式
最新推荐文章于 2024-10-15 18:04:46 发布