Java: Simple Factory Pattern

本文深入探讨了简单工厂模式的概念和应用,介绍了其如何在创建对象的过程中隐藏复杂的业务逻辑,通过实例展示了轮子接口的实现及轮子工厂的运作机制。

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

A Creational Design Pattern
创意设计模式

Defined
Simple factory generates an instance of an object/service for client without exposing any implementation to the client.
In OOP, a factory is an object for creating other objects.
Formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be “new”.

定义
简单工厂为客户端创建对象、服务的实例,而不像客户端公开任何实现。
在oop(面向对象程序设计)中, 工厂是一个可以创建其他对象的对象。
从形式上来看,工厂是一个函数或者是一个方法, 并且掉用某些被假定为 new 的方法可以返回不同形式的原型或者类对象。

Why, When?
Simple factory pattern can be used when creation of an object involves some business logic beyond initialization. It helps in hiding such logic from it.
Well, Show me
Let’s consider that you want to assemble your own custom racing car. But it would be laborious, if every time you need a wheel (yes, you love drifting) you go and make on your own in your garage.
Yeah, you guessed it right. Easy alternate would be to get one from a factory.
Okay, Give me proof of concept!
First of all we need to have a wheel interface.

为什么用,什么时候用
简单工厂模式在创建一个对象并且涉及到一些业务逻辑超出初始化范围的时候被使用。可以帮助隐藏逻辑。
好吧,展示给我看看
我们可以想一想,你想组装你自己的定制的赛车,如果你每次都需要一个轮子,你就去拿并且你也在自己车库里面动手做。(是的,你喜欢慢慢做),但是那会耗费精力。

是的你猜对了,简单的代替方法就是从一个工厂中买一个。
Okey, 证明这个概念
首先我们需要一个轮子的接口:

interface Wheel {
public float getDiameter();
public float getWidth();
}

A CarWheel class will implement it.
一个 CarWheel 类将会实现它

class CarWheel implements Wheel {
protected float diameter;
protected float width;
public CarWheel(float diameter, float width) {
this.diameter = diameter;
this.width = width;
}
public float getDiameter() {
return diameter;
}
public float getWidth() {
return width;
}
}

Here comes the showstopper: WheelFactory class
来了一些搅局者:WheelFactory类

class WheelFactory {
public static Wheel makeWheel (float diameter, float width) {
return new CarWheel(diameter, width);
}
}

Let’s test drive: TestWheelFactory class
让我们来测试:TestWheelFactory 类

**class TestWheelFactory {

public static void main(String args[]) {

    Wheel carWheel = WheelFactory.makeWheel(15, 215);

    System.out.println(carWheel.getDiameter());
    System.out.println(carWheel.getWidth());
}

}**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值