C# Fluentインターフェース
オブジェクト自身を返すメソッドを定義して、Fluentインターフェースを作りました。
メソッドチェーンでピザのサイズやトッピングを設定できます。
using System;
using System.Collections.Generic;
public class Pizza
{
public string Size { get; private set; }
public List Toppings { get; private set; }
public string CheeseAmount { get; private set; }
public Pizza()
{
Toppings = new List();
}
public Pizza Small()
{
Size = "Small";
return this;
}
public Pizza Medium()
{
Size = "Medium";
return this;
}
public Pizza Large()
{
Size = "Large";
return this;
}
public Pizza AddTopping(string topping)
{
Toppings.Add(topping);
return this;
}
public Pizza ExtraCheese()
{
CheeseAmount = "Extra";
return this;
}
public Pizza NormalCheese()
{
CheeseAmount = "Normal";
return this;
}
public override string ToString()
{
return $"Size: {Size}, Cheese: {CheeseAmount}, Toppings: {string.Join(", ", Toppings)}";
}
}
public class Program
{
public static void Main(string[] args)
{
Pizza myPizza = new Pizza()
.Medium()
.AddTopping("Tomato")
.AddTopping("Onion")
.ExtraCheese();
Console.WriteLine(myPizza);
}
}
Size: Medium, Cheese: Extra, Toppings: Tomato, Onion
コメント
コメントを投稿