【问题标题】:OOP design reaching the type outside the class or create instance inside itOOP 设计达到类外的类型或在其中创建实例
【发布时间】:2013-06-06 17:08:41
【问题描述】:

从 SQL Server 填充数据时,到达BObj_SfSn 的最佳方式是什么?

这个

public class BObj_Sub
{
    BObj_Sf _Sn = new BObj_Sf();

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

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

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

【问题讨论】:

  • 无关紧要,但你真的应该重新考虑你的命名约定:)
  • 在一种情况下,您有一个类定义,另一种情况下显示该类的实例化。这两种可比较的填充数据形式如何?

标签: c# class oop design-patterns


【解决方案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 中的代码将保持不变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多