2011-04-27 98 views

回答

1

不,它的做法不错。

这样做可以将所有设置保存在一个地方,以实现简单的持久性。

0

使用可以创建静态类等,实现持久性是很容易和其他执行选项结​​合使用可以使用它的应用是

选项1:

public static void SaveNote(string content) 
     { 
       var fileName = "myNotes.dat"; 
       using (var store = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       if (!store.FileExists(fileName)) 
       { 
        using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store)) 
        { 
         using (var writer = new StreamWriter(writeStream)) 
         { 
          writer.Write(content); 
         } 
        } 
       } 
       } 
      } 

     public static string LoadNote() 
     { 
      var fileName = "myNotes.dat"; 
      try 
      { 

       using (var store = IsolatedStorageFile.GetUserStoreForApplication()) 
       { 
        if (store.FileExists(fileName)) 
        { 
         using (var readStream = new IsolatedStorageFileStream(fileName, FileMode.Open, store)) 
         using (var reader = new StreamReader(readStream)) 
         { 
          return reader.ReadToEnd(); 
         } 
        } 
       } 
      } 
      catch (IsolatedStorageException e) 
      { 

      } 
       return String.Empty; 
     } 

Option 2: 

var note = IsolatedStorageSettings.ApplicationSettings; 
      note.Add("Note", txtNote.Text); 
0

它会更好,不强制一个类是通过设计成为单身人士,而不是通过使用单身人士。让你的数据访问对象(DAO)成为一个普通的类。实现充当对象注册表的Service Locator,让它成为保持DAO奇点的类。

代码示例:

public interface INotesDao { 
    void Save (string s); 
    String Load(); 
} 

public class NotesDaoImpl : INotesDao { 
    // etc. 
} 

public interface IServiceLocator { 
    public TIntfc GetImpl<TIntfc>() { 
     return Activator.CreateInstance (m_Mapping[typeof(TIntfc)]); 
    } 
} 

public static class ServiceLocator { 
    public static IServiceLocator Instance { get; set; } 
} 

// this isn't a robust implementation, just meant to get the point across 
public class MyAppServiceLocatorImpl : IServiceLocator { 

    private Dictionary<Type,Type> m_Mapping = new Dictionary<Type,Type>(); 
    private Dictionary<Type,Object> m_Cache = new Dictionary<Type,Object>(); 

    public MyServiceLocatorImpl() { 
     AddMapping<INotesDao, NotesDaoImpl>(); 
    } 

    private void AddMapping<TIntfc, TImpl>() { 
     m_Mapping[typeof(TIntfc)] = typeof(TImpl); 
    } 

    public TIntfc GetImpl<TIntfc>() { 
     var implType = m_Mapping[typeof(TIntfc)]; 
     if (!m_Cache.ContainsKey (implType)) 
      m_Cache[implType] = Activator.CreateInstance (implType); 
     return m_Cache[implType]; 
    } 
} 

public class MyApp { 
    public MyApp() { 
     ServiceLocator.Instance = new MyAppServiceLocatorImpl(); 

     var dao = ServiceLocator.Instance.GetImpl<INotesDao>(); 
     var notes = dao.Load(); 
     // etc 
    } 
} 

之所以要实现这是单按设计班是很难正确地测试,更何况,它使类稍微复杂些。最好让他们成为愚蠢的班级,让其他班级专门管理各类班级的奇点。

相关问题