1. Adapter mode
If there are many methods in the interface, but only one or a few methods are concerned when using the interface (fewer methods of care),
If conventional means are used, each method needs to be implemented. You can create a type to implement an interface that does not care about the method
An empty implementation, the method of care remains unchanged. After the new class that is defined inherits the abstract class, the method of interest is implemented.
This mode is called the adapter mode. Used in the Handling of button click events in UI design.
--Homework Practice:
Implement adapter pattern design using abstract classes and interfaces. The classes and interfaces involved are buttonlistener (interfaces), respectively,
It contains the click ()/Dbclick ()/keyUp ()/KeyDown () methods.
Buttonadapter (Button adapter class), the default implementation of the non-click () method in the adapter.
Add the AddListener (Buttonlistener L) method to the Button class.
Button Listener Interface
Interface Buttonlistener {
public void OnClick (); Click events
public void Ondbclick (); Double-click event
public void OnKeyDown (); Press the button
public void onKeyUp (); Press to release
}
Button Listener Adapter
Abstract class Buttonadapter implements Buttonlistener {
public void Ondbclick () {}
public void OnKeyUp () {}
public void OnKeyDown () {}
}
Inherit Adapter
Class MyListener extends Buttonadapter {
public void OnClick () {
SYSTEM.OUT.PRINTLN ("I click one!");
}
}
//
Class Yourlistener extends Buttonadapter {
public void OnClick () {
SYSTEM.OUT.PRINTLN ("You click one!");
}
}
Button
Class Button {
The Listener for the button
Private Buttonlistener listener;
Add Listener
public void AddListener (Buttonlistener lsn) {
This.listener = LSN;
}
Simulate Click events
public void Click () {
Handling Click events
Listener.onclick ();
}
Simulate double-click events
public void Dbclick () {
Listener.ondbclick ();
}
}
Test class
Class Adapterdemo {
public static void Main (string[] args) {
Button1
Button btn1 = New button ();
MyListener L = new MyListener ();
Btn1.addlistener (l);
Btn1.click ();
Button2
Button btn2 = New button ();
Yourlistener yl = new Yourlistener ();
Btn2.addlistener (YL);
Btn2.click ();
}
}
2. polymorphic
Multiple forms. The various forms of existence of a certain class of things.
For inherited classes, use the parent class type to refer to the object of the child class.
For an interface, you can use an interface to reference an object that is created by a class that implements the interface.
Why can functions be overwritten, and properties cannot be overwritten? A property is an asset that holds data where the function is behaving, does not hold and stores data, so functions can be overwritten, and properties cannot.
Java Basics-Day 6th