Design Principle: Favor Composition Over Inheritance

本文讨论了在面向对象设计中过度使用继承可能导致的代码冗余问题,并提出使用组合来实现更好的代码复用。通过引入独立的行为类并允许在运行时设置不同的行为,可以实现更灵活和可扩展的设计。

Here at HauteLook, we’re almost constantly interviewing engineers. Not because we have high turnover, but because we’re always growing the team and it’s difficult to find engineers that have the skill level required to join our team. Part of our interview includes a “virtual whiteboard” using a Google doc. And part of that virtual whiteboard exercise includes representing a complex object, showing its properties and methods. We don’t ask for (or care about) valid UML; all that we care about is seeing that the candidate understands object-oriented design (OOD).

Many of our candidates do a wonderful job of constructing a complex hierarchy of inheritance. This gets the job done, but it doesn’t really allow a system to be extensible. When you overuse inheritance, you are basically designing according to assumptions which may seem true at the time, but which will likely not be true as the application is required to change. A key design principle is Encapsulate What Varies. The design principle covered in the post you’re currently reading, Favor Composition Over Inheritance, is one way of following the Encapsulate What Varies principle.

The overuse of inheritance in OOD is common, and is understandable. Many code examples in textbooks show inheritance as the way to make code reusable. And a design that utilizes a nice inheritance hierarchy does appear to make good sense. However, when you need to make a system do something that you hadn’t originally designed it for, the benefits you thought you were getting from an inheritance hierarchy suddenly become the sole reason to refactor your code. When subclasses inherit multiple behaviors from a parent class, they are locked into having those behaviors. The solution is simple, right? Just override those methods and implement the desired behavior for that subclass. But what if another subclass of the same parent has the same issue? Now, if you override the behavior in that subclass too, you have duplicated code.

Let me provide an example. (Note that I’m not going to design classes as we ask for in our whiteboard exercise. Instead, I’ll demonstrate this principle with code.) Let’s say that we want to design a class that plays music. The two concrete examples that we are required to implement are a record player (to play all the awesome 70’s music) and an 8-track player (just because). So we design a base AbstractPlayer class. It might look something like this:

abstract class AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through my speakers!";
    }
 
    public function stop()
    {
        echo "I'm not playing music anymore.";
    }
}

Looks simple enough, right? And our RecordPlayer and EightTrackPlayer classes would inherit from AbstractPlayer and would therefore inherit the play() and stop() methods:

class RecordPlayer extends AbstractPlayer
{
 
}
 
class EightTrackPlayer extends AbstractPlayer
{
 
}

?

Here’s some client code using the RecordPlayer:

$record_player = new RecordPlayer;
$record_player->play(); // echoes "I'm playing music through my speakers!"

?

Awesome! So now, some time goes by, and we get a request to implement a portable cassette player. It would probably be just like the above two concrete classes, but it would need to be able to play through headphones instead of speakers. Here’s what it might look like:

class PortableCassettePlayer extends AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

?

Makes sense, right? Our PortableCassettePlayer inherits from AbstractPlayer and tweaks the play() method a little. Now, fast-forward a couple of decades, and we need to implement an Mp3Player class.

class Mp3Player extends AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

?

Notice that we essentially copied the play() method from the PortableCassettePlayer class. We couldn’t just use the play() method from the base class because the Mp3Player can have headphones plugged in. Maybe we could inherit from the PortableCassettePlayer class, but then we’d inherit a ton of other functionality, such as ejecting a cassette tape, which doesn’t make sense for an MP3 player. The problem here is that inheritance has locked us into certain assumptions, and the design that was intended to encourage code reuse actually causes code duplication.

Instead of using inheritance to reuse functionality, let’s look at a design that uses composition. First, we’ll encapsulate the play() behavior:

interface PlayBehaviorInterface
{
    public function play();
}
 
class PlayBehaviorSpeakers implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music through my speakers!";
    }
}
 
class PlayBehaviorHeadphones implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

?

Now the play functionality is encapsulated into classes. Maybe you’re thinking, “aren’t classes supposed to represent things?” Well, in this case, the thing they’re representing is a behavior.

Let’s see how the Player classes can now use these new behavior classes.

abstract class AbstractPlayer
{
    protected $play_behavior;
 
    abstract protected function _createPlayBehavior();
 
    public function __construct()
    {
        $this->setPlayBehavior($this->_createPlayBehavior());
    }
 
    public function play()
    {
        $this->play_behavior->play();
    }
 
    public function setPlayBehavior(PlayBehaviorInterface $play_behavior)
    {
        $this->play_behavior = $play_behavior;
    }
 
    public function stop()
    {
        echo "I'm not playing music anymore.";
    }
}

?

Notice that the AbstractPlayer has a constructor which sets the default player behavior. It also has a new setPlayBehavior() method. This allows to set whatever play behavior we want at runtime. It also requires implementation of a method called _createPlayBehavior(), so concrete classes are forced to provide their default player behavior. (see my post onRemoving Dependencies With Factory Method.)

Let’s create our Mp3Player class:

class Mp3Player extends AbstractPlayer
{
    protected function _createPlayBehavior()
    {
        return new PlayBehaviorHeadphones;
    }
}

?

The Mp3Player class sets an instance of PlayBehaviorHeadphones as its play behavior. Pretty cool, right? So imagine that a few more years pass, and now our Mp3Player needs to also support playing through a Bluetooth connection. What do we need to change in our Mp3Player class? Think about it for a second. The answer: absolutely nothing! We simply write a new class to encapsulate this new behavior:

class PlayBehaviorBluetooth implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music wirelessly through Bluetooth!";
    }
}

?

This new behavior class can be plugged into the Mp3Player class at runtime if the player is meant to support this functionality. The client code that instantiates the Mp3Player class handles this:

$mp3_player = new Mp3Player;
$mp3_player->play(); //echoes "I'm playing music through headphones!"
$mp3_player->setPlayBehavior(new PlayBehaviorBluetooth);
$mp3_player->play(); //echoes "I'm playing music wirelessly through Bluetooth!"

?

Beautiful, right? Encapsulating behaviors into separate classes gives us true extensibility. In fact, design principles such as Favor Composition Over Inheritance are the reason that we have design patterns. The main pattern used in the above examples is Strategy Pattern. Some other patterns that demonstrate this principle are Observer, Decorator, and State.

Oh, and one more thing to mention: the fact that we were able to drop in new functionality without changing existing code exemplifies another awesome design principle, the Open-Closed Principle. This principle states that classes should be closed to modification but opento extension.

As you think about how to structure your code, I encourage you to keep this principle in mind, and see how it can improve your design. You’ll thank yourself when you have to go back and add new functionality.

原文链接: http://www.hautelooktech.com/2013/02/05/design-principle-favor-composition-over-inheritance/
内容概要:本研究聚焦于绿电直连型电氢氨园区的优化运行,提出一种集成绿色电力直接供给、电解水制氢及氢气合成氨工艺的综合能源系统架构。通过建立包含风光发电、电解槽、氨合成反应器、储氢罐、电网交互及多类型负荷在内的系统模型,综合考虑绿电直供优先、能量梯级利用与多能互补原则,构建以系统综合运行成本最小化为目标的优化调度模型。研究采用Matlab与Python工具进行算法求解和仿真分析,利用实际气象与负荷数据完成案例验证,评估了不同运行策略下系统的经济性、可再生能源消纳能力与碳减排效益,为新型电氢氨一体化园区的规划与运行提供了理论依据和技术支撑。; 适合人群:具备一定电力系统、新能源或化工背景的研究生、科研人员及从事综合能源系统规划与优化工作的工程技术人员。; 使用场景及目标:①用于科研学习,理解电-氢-氨多能转换系统的建模与优化方法;②为工业园区的低碳化、智能化改造提供技术参考与决策支持;③作为开发类似综合能源管理系统的理论基础。; 阅读建议:此资源包含完整的模型代码、数据与论文,使用者应结合代码仔细研读论文中的模型构建部分,重点关注目标函数与约束条件的设计逻辑,并尝试修改参数进行仿真,以深入掌握优化算法在实际系统中的应用。
内容概要:本文深入探讨了RS485通信协议在芯片行业自动化测试系统中的实际开发与应用,涵盖其关键概念、电气特性、通信机制及与Modbus RTU协议的结合使用。文章重点介绍了差分信号完整性设计、主从时序控制、CRC校验与重传机制等核心技术要点,并通过一个基于Python的完整代码实例,展示了如何实现RS485主站对探针台、自动分选机等芯片测试设备的控制与数据采集。此外,还分析了RS485在晶圆探针台、ATE设备集群和环境监控等典型场景的应用,并展望了其与工业以太网融合、智能化诊断、高速化及AI集成的发展趋势。; 适合人群:具备一定嵌入式系统或工业通信基础,从事芯片测试、自动化设备开发及相关领域的研发人员,尤其是工作1-3年希望提升现场总线应用能力的工程师。; 使用场景及目标:①理解RS485在高干扰芯片测试环境中稳定通信的设计原理;②掌握Modbus RTU协议在Python下的实现方法,用于实际控制探针台、Handler等设备;③构建可靠的数据采集与设备控制系统,支持CRC校验、异常处理和日志追踪;④为后续向高速通信和智能诊断系统升级提供技术储备。; 阅读建议:此资源强调实战开发,建议结合硬件环境动手调试代码,重点关注线程锁、CRC计算、帧解析和超时控制等关键环节,在真实产线中验证通信稳定性,并利用日志系统进行故障分析与优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值