C# Design Problem Regarding Data Encapsulation

I have four classes:
1: one that owns the data
2: another that updates the data
3: third that is informed by the first about certain changes of the data
4: last that reads certain properties from the first class

I do not want any other class but the second to be able to update the data.
So what is the best deign patter to use here ?

More on the problem:
1st class is called Schema and it holds a counter of how many instances using that Schema there is.
2nd class is called Factory and it creates/deletes these instances, hence I need to update Schema instance counters and create new Schema objects when necessary.
3rd class is called Config and it holds various shared configurations including information about each new Schema object.
4th class is called View and it simply views Schema information.
Schema objects can be accessed by ID as they are held in a static list.


从程序代码切换到面向对象的代码,并将两个第一类合并成一个具有数据和行为的类。


This is a very abstract description of your scenario, and makes it very difficult to see your problem and what you want to do.

When talking about 'oop', you would typically have a single class that describes an object. In your case, your object is 'the data'. Therefore your first class should be the data and encapsulate any operations on that data.

Classes describe objects - they are not collections of functions. It sounds like your second class is simply a collection of functions.

You will need to further describe your situation because it really doesn't explain much at the moment.


You don't need a design pattern here. Just some principles.

Idea is simple:

object is defined by its behavior
object modifies only state of itself
object guards its state

public class SecondClass{
  public FirstClass First{get;private set;}
  public ThirdClass Third{get; private set;}
  public void DoSomething(){
    First.Something++;
    Second.NotifySomethingHasBeenDone();
  }
}

If relation between 2nd and 3rd class isn't that direct, You might want to use events for notifying:

public class SecondClass{
  public FirstClass First{get;private set;}
  public void DoSomething(){
    First.Something++;
    RaiseEvent<SomethingHasBeenDone>(this);
  }
}

public class ThirdClass:IHandles<SomethingHasBeenDone>{
  public void Handle(SomethingHasBeenDone @event){
    MessageBox("First has {0} something".With(@event.First.Something));
  }
}
链接地址: http://www.djcxy.com/p/6928.html

上一篇: 类型名称后面的括号与新的有什么不同?

下一篇: 有关数据封装的C#设计问题