In order to get a pretty clear idea of user-defined interfaces, I’ll show two concrete classes that implement the same interface. The first one is a simple POST data saver class, which saves and retrieves sequentially data coming from POST forms. The second one consists of a caching class that saves a MySQL query resource in a cache file, and reads data either from the server or the cache file. The caching system is controlled by a time expiry cache trigger. Despite the fact that both classes neither maintain a close relationship nor belong to the same family type, they’ll implement the same interface, so the two classes will be “bridged” through what I call a “DeSerializer” interface. The purpose of the “DeSerializer” interface is to provide two abstract (and of course unimplemented) methods, “getSerializedData()” and “getDeserializedData()”, to be explicitly defined within the previous classes. As you’ll see in a moment, each class will expose these methods, even when they don’t create the same type of objects. To begin, here is the definition of the “DeSerializer” interface: // interface DeSerializer With reference to the above example, I’ve defined the interface simply by prefixing its name with the “interface” keyword. Then I’ve declared the two abstract methods “getSerializedData()” and “getUnserializedData()”, as mentioned previously. From this point onward, each possible class that implements this interface must provide a specific definition for the methods, which implies that many classes can use the same methods, implemented in a different way. Having defined the interface, the next step is to declare the two respective classes. According to this, below is the definition for the “PostSaver” class: // class PostSaver As you can see, the “PostSaver” class implements the “DeSerializer” interface, and its functionality is rather simple. The class obtains an array of data from a post form (initialized through the constructor), then serializes the post array and finally writes the obtained string to a given text file. This task is performed by the “writePostData()” method. Similarly, post data is retrieved through the “readPostData()” method, which unserializes the data stored in the text file and returns the post array. Of course, the point worth mentioning here is the explicit definition of the “getSerializedData()” and “getUnserializedData()” methods within the class, which are listed below: // serialize post data // unserialize post data Now I guess you have a pretty clear idea of the usage of interfaces. The generic functionality defined by the interface is specifically implemented within the class. With the first class already analyzed, the next step consists of defining the second caching class, “MySQLCache”, to demonstrate how it also implements the “DeSerializer” interface. So, keep reading to find out how this is done.
blog comments powered by Disqus |