interface-oriented Programming in Java

Source: Internet
Author: User

Interface-oriented programming is a lot of software architecture design theory advocated by the programming way, learning Java naturally this part, the following is I in the process of learning about how to implement interface-oriented programming in Java knowledge. Share out, there is the wrong place also ask you to correct me.

interface embodies a design philosophy of specification and realization of separation, making full use of the interface can greatly reduce the coupling between the program modules, thus improving the expansibility and maintainability of the system. Based on this principle, it is generally recommended to "interface-oriented" programming, rather than implementing class-oriented programming, to reduce program coupling through interface-oriented programming . here are two common scenarios to demonstrate the benefits of "interface-oriented" programming.

(a) Simple Factory mode

There is a scenario where a Comupter class in the program needs to combine an output device, and now has two options: just let the Comupter class combine a printer property, or let Comupter combine an output property, which is better?

Suppose you let computer combine a printer attribute, and if one day the system needs to be refactored, we need to use betterprinter instead of printer, so we need to open the Computer class source code for modification. If there is only one computer class in the system that combines the printer attribute well, if there are 100 classes in the system that combine printer attributes, even 1000, 10,000 ... Will mean we have to open 100, 1000, 10000 classes to modify, this is how much work!

To avoid this problem, let Comupter combine an output property to completely separate the Comupter class from the printer class. Computer objects are actually composed of printer objects, or Betterprinter objects, which are completely transparent to computer. When the printer object is switched to the Betterprinter object, the system is completely unaffected. The following is the code for this computer class definition.

public class computer

{

Private Output out;

Public computer (Output out)

{

This.out = out;

}

Defines a method that simulates getting a string input

public void Keyin (String msg)

{

Out.getdata (msg);

}

Define a method for simulating printing

public void print ()

{

Out.out ();

}

}

The computer class above has been completely separated from the printer class and is only coupled with the output interface. Computer is no longer responsible for creating the output object, and the system provides an output factory to be responsible for generating the output object. This outputfactory factory class code is as follows:

public class Outputfactory

{

Public Output GetOutput ()

{

return new Printer ();

}

public static void Main (string[] args)

{

Outputfactory of = new Outputfactory ();

Computer C = new computer (Of.getoutput ());

C.keyin ("Crazy Java Handout");

C.keyin ("Light-weight EE enterprise Application Combat");

C.print ();

}

}

A GetOutput method is included in the Outputfactory class that returns an instance of an output implementation class that is responsible for creating an output instance whose object is determined by the method (specifically controlled by the bold part of the method). Of course, you can also add more complex control logic). If the system needs to change printer to the Betterprinter implementation class, just let Betterprinter implement the output interface and change the GetOutput method in the Outputfactory class.

The following is the code for the Betterprinter implementation class, Betterprinter simply modifies the original printer to simulate the improvement of the system refactoring.

public class Betterprinter implements Output

{

Private string[] Printdata = new string[max_cache_line * 2];

To record the number of jobs currently required to print

private int datanum = 0;

public void Out ()

{

As long as there are jobs, continue printing

while (Datanum > 0)

{

System.out.println ("High-speed printer is printing:" + printdata[0]);

Move the job queue whole forward one bit and subtract 1 of the remaining jobs

System.arraycopy (Printdata, 1, printdata, 0,--datanum);

}

}

public void GetData (String msg)

{

if (Datanum >= max_cache_line * 2)

{

SYSTEM.OUT.PRINTLN ("Output queue is full, add failed");

}

Else

{

Add print data to the queue, the number of saved data plus 1.

printdata[datanum++] = msg;

}

}

}

The Betterprinter class above also implements the output interface, so it can also be used as an output object, so we just change the bold part of the GetOutput method of the Outputfactory factory class to the following code:

return new Betterprinter ();

Run the previous Outputfactory.java program again, and discover that the system is running with the Betterprinter object instead of the original printer object.

In this way, all the logic that generates the output object is centrally managed in the Outputfactory factory class, and all classes that need to use the output object are simply coupled to the output interface rather than to the specific implementation class. Even if there are many classes in the system that use the printer object, as long as the GetOutput method of the Outputfactory class is used to generate the output object as Betterprinter object, all of them will instead use the Betterprinter object. All programs do not need to be modified, only the GetOutput method of the Outputfactory factory can be modified.


(ii) Command mode

Consider a scenario in which a method needs to complete a behavior, but the specific implementation of the behavior cannot be determined and must wait until the method is executed. To be specific: suppose there is a way to traverse an array element of an array, but it is not possible to determine how the elements are handled when iterating over the array elements, and you need to specify the specific processing behavior when the method is called.

This request looks a little strange: This method needs not only the ordinary data can be changed, even the method of execution of the body also needs to change, can we put "processing behavior" as a parameter into the method?

For such a requirement, we must pass the "processing behavior" as a parameter into the method, the "Processing behavior" is programmed to implement is a piece of code. So how do you pass this code into the method?

Because Java does not allow code blocks to exist separately, we use a command interface to define a method that encapsulates the "processing behavior". Here is the command interface code.

public interface Command

{

The process method defined in the interface is used to encapsulate the "processing behavior"

void process (int[] target);

}

The command interface above defines a process method that encapsulates the "processing behavior", but this method has no method body-because it is not yet possible to determine the processing behavior.

Here is the processing class that needs to handle the array, which contains a process method that does not determine the processing behavior of the array, so a command parameter is used to define the method, which is responsible for the processing behavior of the logarithm group. The program code for this class is as follows.

public class Processarray

{

public void process (int[] target, Command cmd)

{

Cmd.process (target);

}

}

By means of a command class, the separation of the Processarray class and the concrete "processing behavior" is realized, and the program uses the command interface to represent the processing behavior of the array. The command interface also does not provide true processing, only when it is necessary to invoke the Processarray object process method to actually pass in a command object to determine the processing behavior of the array.

The following procedure demonstrates two ways of handling an array:

public class Testcommand

{

public static void Main (string[] args)

{

Processarray pa = new Processarray ();

Int[] target = {3,-4, 6, 4};

The first time the array is processed, the specific processing behavior depends on Printcommand

Pa.process (Target, New Printcommand ());

System.out.println ("------------------");

The second time the array is processed, the specific processing behavior depends on AddCommand

Pa.process (Target, New AddCommand ());

}

}

The following are the code for the Printcommand class and the AddCommand class, respectively.

public class Printcommand implements Command

{

public void process (int[] target)

{

for (int tmp:target)

{

System.out.println ("element of the iteration output target array:" + tmp);

}

}

}

public class AddCommand implements Command

{

public void process (int[] target)

{

int sum = 0;

for (int tmp:target)

{

sum + = tmp;

}

System.out.println ("The sum of the elements of the array is:" + sum);

}

}

For the two implementation classes of Printcommand and AddCommand, the actual meaningful part is the process (int[] target) method, which is the "processing behavior" of the process method passed into the Processarray class. In this way, the separation of the process method and the "processing behavior" can be realized.

interface-oriented Programming in 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.