Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Template Method

Define algorithm skeleton; subclasses supply steps.

C#

// Base class defines the template method and default hooks
abstract class DataParser
{
	// Template method: invariant algorithm skeleton
	public string Parse() => Open() + Read() + Close();

	// Optional hook steps (can be overridden)
	protected virtual string Open() => "<";
	protected virtual string Close() => ">";

	// Required varying step
	protected abstract string Read();
}

class CsvParser : DataParser
{
	protected override string Read() => "csv";
}

class JsonParser : DataParser
{
	protected override string Read() => "json";
}

// Usage
string a = new CsvParser().Parse();   // ""
string b = new JsonParser().Parse();  // ""
next