Murayama blog.

プログラミング教育なブログ

ビルダー

GW最終日ということで、Effective Javaを読んでみました。

項目2 数多くのコンストラクタパラメータに直面した場合はビルダーを検討する

というのを見て、試しに何かのビルダーを作ってみたくなったので、何か作ってみました。

お題:SQLを実行するクラス的なもの。

package chapter1;

public class SQLCommand {

	String sql;

	public SQLCommand(Builder builder) {
		sql = builder.sb.toString();
	}

	public void execute() {
		System.out.println(sql);
	}

	private static class Builder {

		StringBuilder sb = new StringBuilder();

		public Builder select(String columns) {
			sb.append(" select " + columns);
			return this;
		}

		public Builder from(String table) {
			sb.append(" from " + table);
			return this;
		}

		public Builder where(String conditions) {
			sb.append(" where " + conditions);
			return this;
		}

		public Builder groupby(String columns) {
			sb.append(" group by " + columns);
			return this;
		}

		public Builder orderby(String columns) {
			sb.append(" order by " + columns);
			return this;
		}

		public SQLCommand build() {
			return new SQLCommand(this);
		}
	}

	public static void main(String[] args) {

		SQLCommand simpleCommand = new SQLCommand.Builder().select("*").from(
				"emp").build();
		simpleCommand.execute();

		SQLCommand complexCommand = new SQLCommand.Builder().select(
				"deptno, count(*)").from("emp").where("sal > 500").groupby(
				"deptno").orderby("deptNo").build();
		complexCommand.execute();
	}
}

実行結果

 select * from emp
 select deptno, count(*) from emp where sal > 500 group by deptno order by deptNo

まとめ

ビルダーは楽しい。