0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デザインパターン学習メモ:「Visitor」

Last updated at Posted at 2017-05-29

目的

GoF本より引用する。

あるオブジェクト構造上の要素で実行されるオペレーションを表現する。Visitorパターンにより、オペレーションを加えるオブジェクトのクラスに変更を与えずに、新しいオペレーションを定義することができるようになる。

実装例

GoF本を参考に作成。Productクラスのaccept()を具体的なVisitorインスタンスを渡して実行する。

Productクラスに新しいオペレーションを定義したいときは、新たにVisitorインタフェースを実装したクラスを作成し、visitProduct()メソッドを実装すればよい。

このとき、Productクラスの変更は不要である。

Visitor.java
// Visitor役
public interface Visitor {
	void visitProduct(Product product);
}
PricingVisitor.java
// Concrete Visitor役
public class PricingVisitor implements Visitor {

	@Override
	public void visitProduct(Product product) {
		// Productをつかった任意の処理を実装する
		System.out.println(product.getName());
		System.out.println(product.getPrice());
	}
}
Item.java
// Element役
public interface Item {
	void accept(Visitor visitor);
}
Product.java
// Concrete Element役
public class Product implements Item {
	private String name;
	private int price;

	public Product(String name, int price) {
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return this.name;
	}

	public int getPrice() {
		return this.price;
	}

	@Override
	public void accept(Visitor visitor) {
		visitor.visitProduct(this);
	}
}

参考文献

  • エリック ガンマ、ラルフ ジョンソン、リチャード ヘルム、ジョン プリシディース(1999)『オブジェクト指向における再利用のためのデザインパターン 改訂版』本位田 真一、吉田 和樹 監訳、SBクリエイティブ
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?