用作包含组件的接口的默认实现 [英] default implementation of an interface that is used as a contained component

查看:181
本文介绍了用作包含组件的接口的默认实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口IFoo,我想为它提供一个默认的实现Foo。
Foo可以被其他实现IFoo的类用作包含的类/组件。

I have an interface IFoo for which I want to provide a default implementation Foo. Foo can be used as a contained class/component by other classes that implement IFoo.

IFoo由多个类使用,这些类主要通过转发调用来实现它Foo,但对于某些方法,他们可能会提供自己的实现。

IFoo is used by several classes that mostly implement it by forwarding calls to Foo, but for some methods they may provide their own implementation.

Foo需要访问调用类的(私有)成员。

Foo needs access to (private) members of the calling class.

在方法调用中将这些成员作为参数传递是不可能的,因为它们不是(也不应该是)IFoo接口的一部分。

Passing these members as arguments in method calls is not possible because they are not (and should not be) part of the IFoo interface.

提供公共这些成员的属性仅用于此目的是不必要的,因为它会使调用类的接口过于复杂。

Providing public properties to these members only for this purpose is unwanted because it would make the interfaces of the calling classes overly complex.

问题是:什么是给Foo访问的好设计对这些成员或通常如何实现?是否有任何已知的设计模式?

The question is: what is good design to give Foo access to these members or how is this normally achieved? Are there any known design patterns for this?

编辑:继承不是一个选项,因为实现IFoo的类不能从同一个类继承。

inheritance is not an option because the classes that implement IFoo can't inherit from the same class.

推荐答案

你说没有继承吗?所以基本上你的Foo类不需要实现IFoo,它只需要很容易实现IFoo。为什么不能为方法添加一些参数呢?这样的事情:

No inheritance you say? So basically your Foo class doesn't need to implement IFoo, it just needs to make implementing IFoo easy. Why can't you add some parameters to the methods, then? Something like this:

好的,让我们看看。让我来确定一些方法以确保我做对了:

OK, let's see. Let me make up some methods to make sure I got this right:

interface IFoo
{
    void DisplayTime();
}

和你的FooImplHelper(为了这个例子的目的而变得静态,我不喜欢不知道你的情况是否合理)

And your FooImplHelper (made static just for the purpose of this example, I don't know if it makes sense in your case or not)

public static FooImplHelper
{
    public static void DisplayTime(int UTFOffiset)
    {
        Console.WriteLine(DateTime.UtcNow + TimeSpan.FromHours(UTFOffset));
    }
}

和IFoo实现

public class MyClock: BaseClock, IFoo
{
     public void DisplayTime()
     {
         FooImplHelper.DisplayTime(2);
     }
}

这有意义吗?如果没有,你将不得不提供更多信息。

Does that make sense? If not, you're going to have to give some more information.

Itay,

这篇关于用作包含组件的接口的默认实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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