建造者模式
1 这个模式部分用到工厂模式,不同之处在于,它不止单单满足于生成某种单一的产品,它还要将多个产品组合在一起,成为一个组合。
2 好处是,将一个复杂的组合结构分解出来,每个分解出来的部分单独进行处理,那么这一部分就变得很简单。然后再写一些搭配方法得到你想要的组合。搭配方法有很多种。
3 所以这种模式的主要用法是:给多个人去写产品,产品有一定的约束,然后再在创建者里添加新的组合方案。
public interface I_Item
{
int Price();
}
public abstract class AbsClothing : I_Item
{
public abstract int Price();
public abstract string Material();
}
public abstract class AbsShoes : I_Item
{
public abstract int Price();
public abstract int Size();
}
public class AddiasShoes : AbsShoes
{
public override int Price()
{
return 500;
}
public override int Size()
{
return 42;
}
}
public class NikeShose : AbsShoes
{
public override int Price()
{
return 349;
}
public override int Size()
{
return 41;
}
}
//风衣
public class DustCoat : AbsClothing
{
public override string Material()
{
return "nylon";
}
public override int Price()
{
return 98;
}
}
//毛呢大衣
public class WoolenCoat : AbsClothing
{
public override string Material()
{
return "catton";
}
public override int Price()
{
return 199;
}
}
public class Builder
{
public static int ShowItemPrice(List<I_Item> items)
{
int price = 0;
foreach(var i in items)
{
price += i.Price();
}
Console.WriteLine("Cost:" + price);
return price;
}
public static List<I_Item> Group1()
{
List<I_Item> group = new List<I_Item>();
group.Add(new NikeShose());
group.Add(new WoolenCoat());
return group;
}
public static List<I_Item> Gorup2()
{
List<I_Item> group = new List<I_Item>();
group.Add(new AddiasShoes());
group.Add(new DustCoat());
return group;
}
}
public class Customer
{
//双十一购物
public static void ElevenShopping()
{
List<I_Item> goods = Builder.Group1();
int price = Builder.ShowItemPrice(goods);
}
}