I'm new to Design Patterns, I know the purpose of single responsibility principle, but not 100% sure how it can avoid lots of tiny changes. Below is my example:
//very crude implementation
public class Journal
{
private readonly List<string> entries = new List<string>();
private static int count = 0;
public void AddEntry(string text)
{
entries.Add($"{++count}: {text}");
}
public void RemoveEntry(int index)
{
entries.RemoveAt(index);
count--;
}
public void SaveToDisk(string filename)
{
File.WriteAllText(filename, ToString());
}
}
I know the SaveToDisk
method should not be included in the class, it should be a dedicated class, like PersistenceManager
to handle the file saving.
But why can't I keep the SaveToDisk()
method in Journal
class? if there is any new requirements such as Save the Journal to cloud, then I just add a new method SaveToCloud()
, and any dependent client classes can use SaveToCloud()
, the only modification I need to make is adding SaveToCloud()
in Journal
class, which is totally fine?
Edited: below is my modified version, please spot any design errors:
class Program
{
static void Main(string[] args)
{
Consumer client = new Consumer(new DiskManager("C:\\journal.txt"));
// consumer add text to Journal
client.AddJournal("sometext");
client.SaveJournal();
}
}
public class Journal
{
private readonly List<string> entries = new List<string>();
public void AddEntry(string text)
{
entries.Add(text);
}
public void RemoveEntry(int index)
{
entries.RemoveAt(index);
}
}
public interface IPersistenceManager
{
void Save(Journal journal);
}
public class DiskManager : IPersistenceManager
{
private string filePath;
public DiskManager(string filePath)
{
this.filePath = filePath;
}
public void Save(Journal journal)
{
//XXX.XXX.Save(filePath);
}
}
public class CloudManager : IPersistenceManager
{
private string url;
public CloudManager(string url)
{
this.url = url;
}
public void Save(Journal journal)
{
//XXX.XXX.Save(url);
}
}
public class Consumer
{
private Journal _journal = new Journal();
private IPersistenceManager _manager;
public void AddJournal(string note)
{
_journal.AddEntry(note);
}
public Consumer(IPersistenceManager manager)
{
_manager = manager;
}
public void SaveJournal()
{
_manager.Save(_journal);
}
}