有关带有私有,公共和受保护的构造函数的抽象类的一些问题 [英] Some questions about abstract class with private, public and protected constructors

查看:170
本文介绍了有关带有私有,公共和受保护的构造函数的抽象类的一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个问题:抽象类中的受保护构造函数和公共构造函数有什么区别?

My first question: What is the difference between an protected and a public constructor in an abstract class?

我的第二个问题:如果抽象类具有私有构造函数,这是否有意义?

My second questions: Does it make sense, if the abstract class has an private constructor?

提前谢谢!

推荐答案

一种可能在抽象类上使用私有构造函数的设计:

One possible design that would use a private constructor on an abstract class:

public abstract class BaseClass
{
    private BaseClass(Object param)
    {
        //Do something with parameters
    }

    //Provide various methods that descendant classes will know how to perform

    public static BaseClass FromObject(Object value)
    {
        //Based on object, choose which type of derived class to construct...
    }

    private class HiddenDerivedA : BaseClass
    {
        public HiddenDerivedA(Object value)
            : base(value)
        {
        }
    }

    private class HiddenDerivedB : BaseClass
    {
        public HiddenDerivedB(Object value)
            : base(value)
        {
        }
    }
}

如果派生的实现与用于构造它们的选择逻辑紧密耦合,并且您希望与其余代码保持高度隔离,则此模式很有用.它使您免除了必须支持您明确打算的继承者之外的其他继承者的责任,并允许您将所有私有状态从基类公开给派生类.

This pattern is useful if the derived implementations are tightly coupled to the selection logic used to construct them and you wish to provide a high degree of insulation from the rest of your code. It relieves you of the responsibility of having to support other inheritors besides those you explicitly intended and allows you to expose all private state from the base class to your derived classes.

这篇关于有关带有私有,公共和受保护的构造函数的抽象类的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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