我如何使用全局实例类

时间:2014-05-18 07:30:55

标签: c# .net design-patterns

抱歉,我的英语不好,希望你能理解我...... 我到处都在使用这个DbEntities和其他课程 我如何使用这个全局类?我不想连续创建实例, 示例我可以使用单一模式执行此操作吗?还是全局构造函数?或者我该怎么办?

谢谢

 namespace Crewnetix.Entity.Concrete 
{
    public class Crew
    {
        DbEntities _DbEntities = new DbEntities (); >> object context db entities
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();

     }
}

  namespace Docnetix.Entity.Concrete
{
    public class Document
    {
        DbEntities _DbEntities = new DbEntities ();
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();

  }


  namespace accountingnetix.Entity.Concrete
{
    public class accounting
    {
        DbEntities _DbEntities = new DbEntities ();  
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();        
  }
}

例子我想要它......我认为它

  namespace Global
{
    public static class GlobalInstance
    {
        public static object GetCreateInstance(object class); >> class name
        {
              ...code
            return newInstance;
        }    
    }     
  }
}

  namespace crewnetix
{
    public class crew
    {
       object instance = GetCreateInstance(CertificateItem) >> class name

    }     
  }
}

2 个答案:

答案 0 :(得分:2)

Singleton非常适合您的目标:

//1) make your constructor private

//2) add this code:

private static Your_Class_Name _Instance;
public static Your_Class_Name Instance
{
    get
    {
        if (_Instance == null)
            _Instance = new Your_Class_Name();
        return  _Instance;
    }
}

答案 1 :(得分:1)

你可以让这些类保持静态吗?并标记每个成员您也希望是全局/静态的,例如:

public static class A 
{
  public static string GetSomething() 
  {
      // get something and return it
  }

  public static string AProperty
  {
      // getter and setter
  }
}

使用班级;

A.GetSomething()
var a = A.AProperty;

您不需要创建实例。