jeudi 19 février 2015

Unsure how to use a C# StreamWriter in the decorator pattern

I have a StreamOutput class that looks like this:



class StreamOutput : Output
{
private StreamWriter sink;

public StreamOutput(StreamWriter stream)
{
sink = stream;
}
public string write(Object o)
{
return writeString(o.ToString());
}
public string writeString(String s)
{
try
{
sink.Write(s);
}
catch (IOException)
{
Console.WriteLine("IO Exception");
}
return s;
}
}


The interface from which it inherits is this:



public interface Output
{
string writeString(String s);
}


And I have a few decorators that look like this one:



class LineOutput : Output
{
Output theOutput;

public LineOutput(Output theOutput)
{
this.theOutput = theOutput;
}
public string writeString(String s)
{
return theOutput.writeString(s) + "\n";
}
}


In my Main function, I have an Output object called output, created like this:



StreamWriter writer = new StreamWriter("output.txt");
Output output = new StreamOutput(writer);


that does the decorating by the line



output = new LineOutput(output);


The objective of this decorator is to get a bunch of lines of text from a file, which happens in Main, and then LineOutput double-spaces it all. The problem is, when I write it to a file, it doesn't get double-spaced and, in fact, loses its line formatting altogether.


Any thoughts on if I need to fix the StreamOutput class, and in what way, or if I need to fix the decorators to return something else?


Thanks.


Aucun commentaire:

Enregistrer un commentaire