Advertisement
Lauda

C# - Singleton

Apr 29th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7.  
  8. namespace HCI_Projekat.klase
  9. {
  10.     class Zivotinje
  11.     {
  12.         private static List<ZivotinjskeVrste> zivotinjskeVrste = new List<ZivotinjskeVrste>();
  13.         private readonly string datoteka;
  14.  
  15.         private static Zivotinje instance;
  16.  
  17.         private Zivotinje()
  18.         {
  19.             datoteka = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "zivotinjskeVrste.dat");
  20.             LoadFile();
  21.         }
  22.  
  23.         public static Zivotinje getInstance()
  24.         {
  25.             if (instance == null)
  26.                 instance = new Zivotinje();
  27.  
  28.             return instance;
  29.         }
  30.  
  31.         public List<ZivotinjskeVrste> getZivotinjskeVrste()
  32.         {
  33.             return zivotinjskeVrste;
  34.         }
  35.  
  36.         public void LoadFile()
  37.         {
  38.             BinaryFormatter formatter = new BinaryFormatter();
  39.             FileStream stream = null;
  40.  
  41.             if (File.Exists(datoteka))
  42.             {
  43.                 try
  44.                 {
  45.                     stream = File.Open(datoteka, FileMode.Open);
  46.                     zivotinjskeVrste = (List<ZivotinjskeVrste>)formatter.Deserialize(stream);
  47.                 }
  48.                 catch
  49.                 {
  50.                     //
  51.                 }
  52.                 finally
  53.                 {
  54.                     if (stream != null)
  55.                         stream.Dispose();
  56.                 }
  57.  
  58.             }
  59.             else
  60.                 zivotinjskeVrste = new List<ZivotinjskeVrste>();
  61.  
  62.         }
  63.  
  64.         public void SaveFile()
  65.         {
  66.             BinaryFormatter formatter = new BinaryFormatter();
  67.             FileStream stream = null;
  68.  
  69.             try
  70.             {
  71.                 stream = File.Open(datoteka, FileMode.OpenOrCreate);
  72.                 formatter.Serialize(stream, zivotinjskeVrste);
  73.             }
  74.             catch
  75.             {
  76.                 //
  77.             }
  78.             finally
  79.             {
  80.                 if (stream != null)
  81.                     stream.Dispose();
  82.             }
  83.         }
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement