Java design patterns - Visitor Pattern

Article Directory

background

It has recently been constructed in-depth analysis of ancient iron, and even the bones were spared. Why did the ancient iron so popular? Today is no exception, take a look at the design ideas of ancient iron, you will understand why the ancient iron so strong! Here, I'll give you instill a wave of chicken soup, the saying goes: into a major event sloppy. Successful people should spend time and energy on the most important things on their own, and not for some stupid trivial waste of time.
The main work of ancient iron is action, attack, this non-repair job is usually outsourced to someone else did it, only need to provide an interface accessible for others to help repair the ancient iron, specific implementation details are as follows.

achieve

Body abstract class

/**
 * 机体抽象类
 */
public abstract class Robot {
	
	private String name;

	/**
	 * 攻击是机体自己做的事情
	 */
	abstract void attack();

	/**
	 * 维修是别人帮忙做的事情
	 * 
	 * @param visitor 交给维修人员(访问者)来做
	 */
	abstract void repair(IVisitor visitor);

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

Ancient iron

/**
 * 又是我们的古铁..
 */
public class AncientIron extends Robot {

	@Override
	void attack() {
		System.out.println("自己操纵古铁还是非常有乐趣的,左轮打桩机!");
	}

	@Override
	void repair(IVisitor visitor) {
		visitor.visit(this);
	}

}

Visitors Interface

public interface IVisitor {

	/**
	 * 访问机体的功能
	 */
	void visit(Robot robot);
}

Maintenance staff

public class RobotRepairer implements IVisitor {

	@Override
	public void visit(Robot robot) {
		System.out.println(robot.getName() + ",你好!所谓成大事者不拘小节,维修这种事情还是让我们修理工做吧!");
	}

}

test

public class Test {

	public static void main(String[] args) {
		IVisitor repairer = new RobotRepairer();

		Robot ancientIron = new AncientIron();
		ancientIron.setName("古铁");
		ancientIron.attack();
		ancientIron.repair(repairer);
	}
}

Test Results

自己操纵古铁还是非常有乐趣的,左轮打桩机!
古铁,你好!所谓成大事者不拘小节,维修这种事情还是让我们修理工做吧!

to sum up

Visitors model has obvious advantages, is to follow the principle of single responsibility, assume a class there are some non-job approach, consider these methods to the visitors to achieve. So, if logic implemented after there is a change, visitors only need to change, without having to do much to change this class.

Guess you like

Origin blog.csdn.net/cblstc/article/details/93708835