Java设计模式教程 - Java设计模式 - 工厂模式

本文介绍工厂模式这一创建型设计模式,并通过实例演示了如何利用工厂模式创建不同类型的形状对象,如圆形、矩形等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工厂模式是一种创建型模式,因为此模式提供更好的途径去创建对象。
在工厂模式里,我们不用向客户端暴露创建逻辑而能创建对象。
[b][size=large]例子[/size][/b]
下面展示如何使用工厂模式去创建对象。
该工厂模式将创建形状的对象,比如圆、长方形。
首先我们设计一个表示形状(Shape)的接口。

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,它就创建一个Circle对象。

public class ShapeFactory {

//use getShape method to get object 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;
}
}

以下代码包含main方法,而它通过传递形状的type信息而使用工厂类去取得具体类的对象。

public class Main {

public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();

//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");

//call draw method of Circle
shape1.draw();

//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");

//call draw method of Rectangle
shape2.draw();

//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");

//call draw method of circle
shape3.draw();
}
}

以上代码生成以下结果。


Inside Circle::draw() method.
Inside Rectangle::draw() metod.
Inside Square::draw() metod.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值