Created
January 3, 2025 09:03
-
-
Save davepcallan/35b9db86e1dc893e7001fe40a612f6bd to your computer and use it in GitHub Desktop.
Template Method Pattern C# simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class HotelBookingTemplate | |
{ | |
// Template Method | |
public void BookRoom() | |
{ | |
SelectRoom(); | |
ProcessPayment(); | |
ApplyDiscount(); | |
SendBookingConfirmation(); | |
} | |
// Common for all subclasses | |
private void SelectRoom() | |
{ | |
Console.WriteLine("Room selected."); | |
} | |
// Must be implemented by subclasses | |
protected abstract void ProcessPayment(); | |
// Hook (optional override by subclasses) | |
protected virtual void ApplyDiscount() { } | |
// Common for all bookings | |
private void SendBookingConfirmation() | |
{ | |
Console.WriteLine("Booking confirmation sent."); | |
} | |
} | |
// Standard booking without discount | |
public class StandardBooking : HotelBookingTemplate | |
{ | |
protected override void ProcessPayment() | |
{ | |
Console.WriteLine("Processing payment at standard rate."); | |
} | |
} | |
// Premium booking with discount | |
public class PremiumBooking : HotelBookingTemplate | |
{ | |
protected override void ProcessPayment() | |
{ | |
Console.WriteLine("Processing payment at premium rate."); | |
} | |
protected override void ApplyDiscount() | |
{ | |
Console.WriteLine("Applying 10% discount for premium customers."); | |
} | |
} | |
// Client Code | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Standard Booking Process:"); | |
HotelBookingTemplate standardBooking = new StandardBooking(); | |
standardBooking.BookRoom(); | |
Console.WriteLine("\nPremium Booking Process:"); | |
HotelBookingTemplate premiumBooking = new PremiumBooking(); | |
premiumBooking.BookRoom(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment