访问者模式的实现
访问者模式就是针对不同的资源设置不同的访问权限, 反转这访问权限的设置位置,从而达到不修改资源来控制访问权限的目的.
- 先设置一个元素材资源和元访问权限
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将操作仅放在需要它们的应用程序中 定义对象结构的类很少更改,但是您经常想在该结构上定义新的操作。更改对象结构类需要重新定义所有访问者的接口,这可能会导致成本高昂。如果对象结构类经常更改,那么最好在这些类中定义操作
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。