简体   繁体   中英

Visitor pattern, not all visitors have a reasonable implementations for all methods in the interface

I have an interface Serializable . This class have methods for each Item subclass in my application. However not all classes that implements Serializable have a reasonable implementation of the serialize method. Some of the serializers should not be able to serialize all the different objects because of security constraints in my application.

How should I solve this? Should I serialize a message that says "Serializer can't serialize object because of security constraints." or should I throw an RuntimeException? Or are there other ways of "fixing" this?

You would violate one important principle with your logic: Interface Segregation Principle

The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule.

So, I would create two distinct base classes to achieve your requirement:

  • Item
  • SerializableItem

And your visitor would only rely on SerializableItem objects:

public void visit(SerializableItem sItem) 

Of course, it is possible to gather only common behaviour (unrelated to serialization so) of both classes within a kind of AbstractItem , as long as the visitor doesn't deal with it.

Throwing UnsupportedOperationException("Non serializable") is a first guess. Of course it would be awesome to discover that at compile time, but Visitor pattern was not designed for that.

A class that won't provide a reasonable implementation for Serializable shouldn't implement it. Anyway the question is quite unclear. Does the interface Serializable declare the accept() method in your setup? It shouldn't. If it is possible that unserializable items are a special subclass of item you could just not implement the visit(MyNotSerializableItem) in the Visitor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM