在下面的章节中,我们将展示如何使用工厂模式来创建对象。
由工厂模式创建的对象将是形状的物体,如圆形,矩形。
首先,我们设计代表形状的接口。
public interface Shape {
void draw();
}
然后,我们创建具体的类实现该接口。
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(\"Inside Rectangle::draw() method.\");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println(\"Inside Square::draw() method.\");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println(\"Inside Circle::draw() method.\");
}
}
核心工厂模式是工厂类。下面的代码演示如何创建一个工厂类Shape对象。
该ShapeFactory类创建基于传递到getShape()方法的字符串值Shape对象。如果字符串值是圆,它会创建一个Circle对象。
public class ShapeFactory {
//use getShape method to get of type shape
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();
} else if(shapeType.equalsIgnoreCase(\"SQUARE\")){
return new Square();
}
return null;
}
}
下面的代码有mian方法,它采用工厂类传递一个信息,如类型,以获得具体类的对象。
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape(\"CIRCLE\");
//call draw method of Circle
shape1.draw();
//get an of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape(\"RECTANGLE\");
//call draw method of Rectangle
shape2.draw();
//get an of Square and call its draw method.
Shape shape3 = shapeFactory.getShape(\"SQUARE\");
//call draw method of circle
shape3.draw();
}
}
继续阅读与本文标签相同的文章
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
-
量子信息和量子技术白皮书合肥宣言在中科大发布
2026-05-14栏目: 教程
-
微信悄悄更新一新功能,来看看!
2026-05-14栏目: 教程
-
打破三大运营商垄断,第四大运营商终于来了!
2026-05-14栏目: 教程
