Java设计模式(10) —— 状态

本文介绍了如何在Java中实现状态模式,通过一个具体的银行账户取款和存款的例子,展示了如何利用状态模式来处理不同状态下的行为变化,避免了在Context类中使用复杂的条件逻辑。文章详细解释了Context、State接口和不同ConcreteState子类的职责,并提供了相应的代码实现。

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

State

 

Intent
Allow an object to alter its behavior when its internal state changes.

How to
1.Context delegates state-specific requests to the current ConcreteState object.
2.Clients can configure a context with State objects. Once a context is configured, its clients don't have to deal with the  State objects directly.
3.Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances.

Context
defines the interface of interest to clients.
maintains an instance of a ConcreteState subclass that defines the current state.
State
defines an interface for encapsulating the behavior associated with a particular state of the Context.
ConcreteState subclasses
each subclass implements a behavior associated with a state of the Context.

Known cases
Credit Account
Process

UML


 

假设账户有三种状态:

1.如果没透支,则取款不收取费用(NonfeeState)

2.如果透支数小于等于200,则取款费用为2元(FeeState)

3.如果透支数多于500,则不允许取款(OverdrawState)

 

代码:

 

说明:

(1)如果此例不运用状态模式,则会在Account中的withdraw和diposit方法中有if-else语句(如果发现一个类中有许多方法有相同的条件逻辑判断,可能表示这个类可以重构成状态模式)

(2)由于各个State子类无状态,因此全局只需使用一个实例即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值