设想形式之访问者形式
2019-11-18杂谈搜奇网37°c
A+ A-接见者形式的完成
接见者形式就是针对差别的资本设置差别的接见权限, 反转这接见权限的设置位置,从而到达不修正资本来掌握接见权限的目标.
- 先设置一个元素材资本和元接见权限
public class unionLevel {
public String getLevelName(unionVisitor visitor){
return "see union level";
};
}
public interface unionVisitor {
/**
* 看第一级素材
* @return
*/
default String seeLevelOne(unionLevel level){
return level+" forbidden";
}
/**
* level two
* @return
*/
default String seeLevelTwo(unionLevel level){
return level+" forbidden";
}
/**
* level three
* @return
*/
default String seeLevelThree(unionLevel level)
{
return level+" forbidden";
}
}
- 设置多级素材继续元素材
public class LevelOne extends unionLevel{
@Override
public String getLevelName(unionVisitor visitor) {
System.out.println(visitor.seeLevelOne(this));
return super.getLevelName(visitor);
}
@Override
public String toString() {
return "levelone";
}
}
- 设置多级权限完成元权限
public class VisitorOne implements unionVisitor{
/**
* 看第一级素材
*
* @return
*/
@Override
public String seeLevelOne(unionLevel level) {
return "VisitorOne can see "+level;
}
}
- 写个测试类(其他元素和素材照着上面demo写就行)
public class start {
public static void main(String[] args) {
LevelTwo two = new LevelTwo();
two.getLevelName(new VisitorOne());
two.getLevelName(new VisitorTwo());
two.getLevelName(new VisitorThree());
}
}
总结
寻常不怎么喜好写总结的,然则说假如运用的时刻照样会去翻一下他的定义。以防止本身弄错了都不晓得,实在关于接见者形式来讲,最大的优点就是对权限这边的解放(不过你假如资本级别会随意变动而权限设置不会随意变动的话,能够将这个设想反过来。毕竟设想是死的而人是活的。一定要写成对完成越发轻易的代码出来)
接见者形式
是23种基础设想形式中的一种,属于行动型设想形式。维基百科定义:Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.(示意要在对象构造的元素上实行的操纵。接见者可以让您定义新操纵,而无需变动其所操纵元素的类)
适用范围
Use the Visitor pattern when
- an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes
- many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them
the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes
在以下情况下运用接见者形式 * 一个对象构造包括很多具有差别接口的对象类,而且您愿望依据这些对象的详细类对这些对象实行操纵 * 须要对对象构造中的对象实行很多差别且不相干的操纵,而且您要防止运用这些操纵“污染”它们的类。访客能够经由过程在一个类中定义相干操纵来将它们坚持在一起。 * 当很多应用程序同享对象构造时,请运用Visitor将操纵仅放在须要它们的应用程序中 定义对象构造的类很少变动,然则您常常想在该构造上定义新的操纵。变动对象构造类须要从新定义一切接见者的接口,这可能会致使本钱奋发。假如对象构造类常常变动,那末最好在这些类中定义操纵
https://github.com/fulln