防止/限制方法继承 [英] Prevent/Restrict Method Inheritance

查看:45
本文介绍了防止/限制方法继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中许多对象都扩展了一个抽象类,该类定义了诸如 create() edit() retrieve()delete().由于每个子类对这些函数使用相同的逻辑,抽象类定义了默认行为,并且在少数需要增强的情况下,子类可以覆盖或使用我内置的钩子.

I have an application in which a number of objects are all extending an abstract class which defines methods like create() edit() retrieve() and delete(). Since each of the child classes use the same logic for these functions, the abstract class defines that default behaviour, and in the few cases where it needs to be augmented, the child classes can override or use the hooks I've built in.

现在我遇到了一些子类需要不可变的情况,这意味着它们不应该具有 edit()delete()方法.这对我来说听起来像是一个名为 immutable 之类的接口的工作,不可变类可以实现它.问题是接口不会阻止方法被调用,它们只是强制方法的存在.所以这显然行不通.

Now I'm having the situation where some of the child classes need to be made immutable, meaning that they shouldn't have edit() or delete() methods. This need sounds to me like a job for an interface named something like immutable which the immutable classes could implement. Problem is that interfaces don't stop methods from being called, they just enforce a method's existence. So this is obviously not going to work.

创建两个父类,一个用于可变对象,一个用于不可变对象是丑陋的,并且可能会在维护方面提出问题.我可以让不可变对象用一个什么都不做的空方法覆盖有问题的方法,但这看起来也很混乱,就像我当时没有做正确的 OOP.

Making two parent classes, one for mutable objects and one for immutable ones is ugly and is probably asking for problems down the line which maintenance. I could have the immutable objects override the offending methods with an empty method that did nothing, but that also seems messy and like I'm not doing proper OOP at that point.

那么您认为允许大量类都继承一组方法的最佳方法是什么,但其中一些不继承所有方法?(有问题的应用程序是用 php 编写的,但任何语言的通用 OOP 技术仍然会有所帮助.

So what would you suggest as the best way to allow a large set of classes to all inherit a set of methods, but for some of them to not inherit all of the methods? (The application in question is written php, but general OOP techniques from any language can still be helpful).

推荐答案

创建一个不可变的基类作为基类的子类.immutable-base 应该实现 final 覆盖 edit() 和 delete() 什么都不做或抛出错误.

create an immutable-base class as a child of the base class. the immutable-base should implement final overrides of edit() and delete() which do nothing or throw an error.

Final,保证所有不可变的子级都不能编辑或删除

Final, so that all immutable children are guaranteed not to be able to edit or delete

这个策略的好处

  • 通过测试 instanceof immutable-base 轻松检查对象是否不可变

  • easily check if an object is immutable by testing for instanceof immutable-base

通过修改对象的扩展内容,轻松地将对象从不可变的状态更改回来

easily change objects from immutable and back again by modifing what it extends

这篇关于防止/限制方法继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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