1. 程式人生 > >Builder構造器模式示例學習

Builder構造器模式示例學習

假設肚子餓了要吃飯,吃飯要吃菜,可是做菜很麻煩,要放油、調料、肉菜等等,對於不喜歡做菜的人來說,每次都要按固定程式炒一次菜很無趣

所以我們希望一個炒菜機

public class Food
{

	private final int mode;
	private final String oil;
	private final String seasoning;
	private final boolean meat;
	private final String vegetables;

	// 炒菜機
	public static class Builder
	{
		private final int mode;
		private final String oil;
		private String seasoning = "lajiao";
		private boolean meat = false;
		private String vegetables = "qingjiao";

		//假設模式和放油是必須的
		public Builder(int mode, String oil)
		{
			this.mode = mode;
			this.oil = oil;
		}

		public Builder seasoning(String seasoning)
		{
			this.seasoning = seasoning;
			return this;
		}

		public Builder meat(boolean meat)
		{
			this.meat = meat;
			return this;
		}

		public Builder vegetables(String vegetables)
		{
			this.vegetables = vegetables;
			return this;
		}

		public Food cook()
		{
			return new Food(this);
		}
	}

	private Food(Builder builder)
	{
		mode = builder.mode;
		oil = builder.oil;
		seasoning = builder.seasoning;
		meat = builder.meat;
		vegetables = builder.vegetables;
		System.out.println("mode: " + mode + "; oil: " + oil + "; seasoning: "
						+ seasoning + "; mear: " + meat + "; vegetables: "
						+ vegetables);
	}
}


如此,再需要做菜的時候只需要如下呼叫:

{
	Food.Builder builder = new Food.Builder(0, "huashengyou");
	builder.seasoning("tang");
	builder.meat(true);
	builder.vegetables("dabaicai");
	Food food = builder.cook();
}