Delegate proxy callback, internal class and anonymous internal class callback (Closure callback) in Java programming, and delegate proxy callback

Source: Internet
Author: User

Delegate proxy callback, internal class and anonymous internal class callback (Closure callback) in Java programming, and delegate proxy callback

Recently, I have been reading Java related things, because in iOS development, delegate proxy callbacks, Block callbacks, or closure Callbacks are often used in Objective-C and Swift. Next, let's take a look at how the delegate proxy callback and closure callback are implemented in Java. Although these two technical points are not difficult to implement, this callback is particularly useful when Encapsulating some public components. So today, it is necessary to talk about the delegate proxy callback and closure callback in Java separately.

This blog is still based on examples. Let's talk about the implementation and use cases of delegate proxy callback, and then talk about using anonymous internal classes for callback, in fact, it is what we often call the "closure" callback. The implementation of closure callback is actually the use of anonymous internal classes. Since this blog uses anonymous internal classes, let's talk about the internal classes in Java.

 

1. Delegate proxy callback

In iOS development, we often use delegate proxy callbacks, such as TableView and CollectionView. These advanced controls rely on delegate callback to complete some configurations. Of course, the delegate proxy callback in Java is also very useful. Next let's take a look at the delegate proxy callback in Java. Of course, the delegate proxy callback in Swift or OC relies on the "protocol". The "protocol" in Swift or OC is actually the "interface" in Java ". Therefore, the delegate proxy callback in Java is still implemented based on the "interface.

 

1. Class Diagram

First, we will give the class diagram of this part of the instance, and then we will design and implement our specific code according to the class diagram below. Below is the Demo class diagram designed by the Department. Of course, we can intuitively see from the class diagram that this example is relatively simple, and there are two classes of an interface in total. CustomDelegate is the interface to be implemented by the proxy class, which contains the method to be implemented by the proxy class.

From the class diagram below, we can see that the proxy class FirstClass implements the CustomDelegate proxy interface and implements relevant proxy methods. SecondClass depends on the CustomDelegate interface, that is, any class that implements the CustomDelegate interface can be used as the proxy of SecondClass. FirstClass contains SecondClass attributes, and FirstClass implements the CustomDelegate interface. In FirstClass, we specify the proxy class of the secondClass object as FirstClass, we will introduce it later in specific implementation.

  

 

2. Code Implementation

Based on the above class diagram, we can easily provide the corresponding code implementation. Next, we will provide specific code implementation based on the class diagram above.

(1) CustomDelegate code implementation

The code segment below is the specific implementation of CustomDelegate. Of course, the implementation of this interface is relatively simple, just a setValue (String value) method. The specific function of this method is to call back corresponding parameters. We will use this method below.

package com.zeluli.callback.delegate;public interface CustomDelegate {    public void setValue(String value);}

 

(2) code implementation of SecondClass

After CustomDelegate is implemented, let's implement the specific code of SecondClass. The code snippet below is the specific code implementation of SecondClass. We can clearly see from the specific implementation that the SecondClass class has a private delegate attribute, which is of the CustomDelegate type, so SecondClass depends on the CustomDelegate type.

In the constructor of SecondClass, we specify a specific object for delegate and call the begin () method. The begin () method is also relatively simple, that is, using a self-contained timer in Java, and then executing the setValue () method of the delegate object at a specific interval, and pass the current time to the setValue () method.

Package com. zeluli. callback. delegate; import java. text. simpleDateFormat; import java. util. date; import java. util. timer; import java. util. timerTask; public class SecondClass {private CustomDelegate delegate; public SecondClass (CustomDelegate delegate) {this. delegate = delegate; this. begin ();} public void begin () {TimerTask task = new TimerTask () {@ Override public void run () {delegate. setValue (getNowDate (); // execute the delegate proxy callback method }}; long delay = 0; Timer timer = new Timer (); timer. scheduleAtFixedRate (task, delay, 1000);} private String getNowDate () {Date currentTime = new Date (); SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); String dateString = formatter. format (currentTime); return dateString ;}}

 

(3) create FirstClass

Next we will create the delegate proxy class, that is, our FirstClass class. The Code is also relatively simple. The FirstClass class implements the CustomDelegate method, and then specifies the proxy object for the secondClass object to be the object of the current class. The Code is as follows.

1 package com. zeluli. callback. delegate; 2 3 public class FirstClass implements CustomDelegate {4 private SecondClass secondClass; 5 6 public void beginRunSecondDelegateMethod () {7 if (this. secondClass = null) {8 this. secondClass = new SecondClass (this); 9} 10} 11 12 // method of the secondClass callback to be executed 13 @ Override14 public void setValue (String value) {15 System. out. println ("Second Class callback value:" + value); 16} 17 18}

 

3. Test Cases and running results

Next, let's take a look at the test cases and running results of the above Code. The code snippet below is our test case. The code is relatively simple. It is to instantiate a FirstClass Class Object firstObj, and then call the corresponding method to specify the proxy method for secondClass, as shown below.

package com.zeluli.callback.delegate;public class Main {    public static void main(String[] args) throws InterruptedException {        FirstClass firstObj = new FirstClass();        firstObj.beginRunSecondDelegateMethod();    }}

Below is the running result of the above Code. We can see that the setValue () method in FirstClass will be executed on a regular basis.

  

 

 

Ii. Closure callback

We have implemented the delegate proxy callback above. Next we will modify the above example. Change it to the implementation method of the anonymous internal class, that is, use the closure form to implement callback. We only need to talk about FirstClass modification. Modify the delegate proxy callback to the form of the closure callback. The code snippet below is the source code of the modified FirstClass class.

The source code below shows that FirstClass does not implement the CustomDelegate interface. When specifying a delegate proxy object for a SecondClass object, we pass in an anonymous internal class object, and the type of this object is CustomDelegate. This is also one of the usage methods of anonymous internal classes.

  

The test cases and running results of the modified Code are the same as those of the delegate proxy callback method in the first part. We will not repeat it too much here.

 

 

Iii. Internal class

Now that we use anonymous internal classes, let's take a look at the content of the internal classes. Internal classes, as the name implies, are internal classes defined in interfaces, classes, methods, and other structures. The anonymous internal class is an internal class without a name, which is quite understandable. Below we will look at the specific use cases and rules of internal classes from the examples of the iterator and the factory model. Of course, the two examples have different internal classes.

 

1. Internal classes in the iterator

In our previous blog, we talked about the Iterator Pattern in detail. For more information, see design Pattern (10): Learn about the Iterator Pattern in the cinema). Of course, the previous iterator is implemented using Swift3.0. Today, we use Java internal classes to implement a Java iterator.

 

(1) iterator Interface

According to the previous introduction to the iterator routine, we should first create the iterator interface. The Selector below is the iterator interface we created.

  • The end () method is used to determine whether the sequence has reached the ending point.
  • The current () method is used to obtain the value of the lower mark in the current sequence.
  • The next () method moves the subscript to the next position.

To unify the usage of the iterator, all the iterators must follow this interface. The Code is as follows.

  

 

(2) create a sequence class and an internal class of the iterator

The Sequence class is created below. The items array in this class is used to store elements, and the next attribute points to the subscript of the current value. In the Sequence class, apart from attributes, constructors, and methods, we also define an internal class SequenceSelector.

The SequenceSelector class is the iterator of the Sequence class, And the SequenceSelector must implement the Selector interface of the iterator. Note that in the SequenceSelector of the internal class, you can directly access the member attributes and methods of the Sequence class of the outer class. Because both the member attributes of the internal class and Sequence class are in the Sequence class domain.

Of course, the logic of the code below is relatively simple, mainly for operations on the items array. The Code is as follows.

  

 

(3) Use of the above iterator

After defining the iterator, let's take a look at the usage of the iterator. First, we create a sequence object, and then add the object to the sequence object through the for loop. Then we get the corresponding iterator object from this sequence object, and then the operator iterator traverses the sequence. The procedure is as follows.

  

 

 

2. Anonymous internal class in factory Mode

After talking about the internal classes of the iterator, let's take a look at the anonymous internal classes in the factory mode. In our previous blog, we talked in detail about the specific content of the factory model. For details, see design mode (4 ): explore simple factories, factory methods, and abstract factory models from the "plant". This blog will show you how to use anonymous internal classes in the factory model.

(1) class diagram

First, let's take a look at the specific class diagrams of the cases involved in this section. below is the class diagrams we will introduce.

  • Service Interface: first, let's take a look at the Service interface, which is the interface to be implemented by all specific implementation classes. Define the specific method declaration. All our implementation classes must inherit from this interface.
  • ServiceFactory interface: this interface is implemented by all factory classes, because our factory classes are embodied in the form of anonymous internal classes, all of these interfaces are of the "anonymous internal class" type.
  • Implemention1 and 2: These two classes are our specific implementation classes, and our factory is responsible for instantiating these two classes.
  • Factories class: this class is responsible for calling the factory method to create the relevant instance and executing the related methods of the instance.

  

 

(2) Implementation of the Service and ServiceFactory Interfaces

The implementation code of these two interfaces is relatively simple, so I will not go into details here. The specific code is as follows:

 1 package com.zeluli.innerclass.factory; 2  3 public interface Service { 4     void method1(); 5     void method2(); 6 } 7  8 ====================================================== 9 10 package com.zeluli.innerclass.factory;11 12 public interface ServiceFactory {13     Service getService();14 }

 

(3) Implementation of Implementation-related classes

The implementation of Implementation1 and Implementation2 is similar. Let's talk about the specific code of Implementation1. From the code snippet below, we can see that Implementation1 class implements the Service interface and provides the implementation of related methods in the interface. In the Implementation1 class, there is a static ServiceFactory variable factory of the ServiceFactory type. Factory references an anonymous internal Class Object of the ServiceFactory type. This anonymous internal class is an engineering class. One of the methods is responsible for creating the current peripheral class, that is, the Implementation1 class object. The specific implementation is as follows.

  

 

(4) Implementation of the Factory class

Next, let's take a look at the implementation of the Factory class. The Factory is responsible for getting the corresponding object from the Factory, and then executing the related methods of the object. The code is relatively simple, so we will not repeat it too much.

  

 

 

(5) test cases and running results

Next, let's take a look at the test cases and output results of the above instances, as shown below:

  

 

Today's blog is here, and the next blog will continue to talk about Java.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.