OOP设计到达类外部的类型或在其中创建实例

时间:2013-06-06 17:08:41

标签: c# class oop design-patterns

从SQL Server填充数据时,从BObj_Sf Sn到达public class BObj_Sub { BObj_Sf _Sn = new BObj_Sf(); public BObj_Sf Sn { get { return _Sn; } set { _Sn = value; } } } 的最佳方法是什么?

这一个

BObj_Sub sub = new BObj_Sub
 {
    Sf = new BObj_Sf { SAd = SAd },
 };

或者这是ooP的一个更好的方面吗?

{{1}}

1 个答案:

答案 0 :(得分:1)

我相信您的问题与良好的编程习惯和there could be multiple solution or design technique for this question更相关。

我会创建这样的类 -

// create interface for providing {x} features
public interface IBObj_Sf
{
   ...
   ...
}

// create class which provides {x} features of IBObj_Sf interface
public class BObj_Sf : IBObj_Sf
{
   ...
   ...
}

// now implement BObj_Sub class like -
public class BObj_Sub
{
        // mark as readonly depending it is modifiable or 
        // not withing BObj_Sub's lifecycle
        private readonly IBObj_Sf _Sn; 

        public BObj_Sub(IBObj_Sf sn)
        {
            _Sn = sn;
        }

        public BObj_Sf Sn
        {
            get { return _Sn; }
            private set { _Sn = value; }
        }
}

<强>用法:

BObj_Sf sf = new BObj_Sf();
BObj_Sub sub = new BObj_Sub(sf);

优势明天,如果您想将BObj_Sf更改为某个新课程BObj_Xf,则只会更改以下行以及您的新课程。 -

BObj_Xf xf = new BObj_Xf();
BObj_Sub sub = new BObj_Sub(xf);

BObj_Sub中的代码将保持不变。