我可以使用继承而不是在策略模式中实现接口吗? [英] Can i use inheritance instead of implement an interface in strategy pattern?

查看:68
本文介绍了我可以使用继承而不是在策略模式中实现接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从图片中,我可以使用继承而不是实现接口吗?

From a picture, Can i use inheritance instead of implement an interface?

我的意思是从" ConcreteStrategyA ConcreteStrategyB 实现 Strategy 接口"更改为" ConcreteStrategyA ConcreteStrategyB 扩展了 Strategy 类"

I mean change from "ConcreteStrategyA and ConcreteStrategyB implements Strategy Interface" to "ConcreteStrategyA and ConcreteStrategyB extends Strategy Class"

它是否仍然可以正常工作或出现问题?

Is it still work well or have some problem?

如果仍然可以正常工作,我的下一个问题是为什么大多数人都喜欢使用界面?"

If it still work well my next question is "Why most people prefer to use interface?"

推荐答案

绝对.当您希望派生策略共享一些通用代码时,继承通常与抽象基类一起使用.

Absolutely. Inheritance is most often used with an abstract base class, when you want your derived strategies to share some common code.

人们喜欢使用接口或抽象类而不是具体的基类,因为:

People prefer to use interfaces or abstract classes over concrete base classes because :

  • 使用依赖倒置方法,类需要与其策略进行松散耦合.它只需要知道该策略已履行合同,而又不想知道其实施细节.接口和抽象类是在不指定实现的情况下定义契约的一种优雅而最少的方法.

  • With a Dependency Inversion approach, a class needs loose coupling to its Strategy. It only needs to know that the Strategy fulfills a contract, but doesn't want to know about its implementation details. Interfaces and abstract classes are an elegant and minimal way to define a contract without specifying the implementation.

大多数时候实例化基本的Strategy类是没有意义的,因为它是一个通用的抽象概念-实际上,最好不要实例化.

It doesn't make sense to instantiate the base Strategy class most of the time, because it's a general, abstract concept -- in fact, it's better if you forbid instantiating it.

这篇关于我可以使用继承而不是在策略模式中实现接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆