1. Background
Chase mm example, boy chase mm, need to send gifts gift, have flower,ring inherit from gift;
and warmgift warm gifts, wildgift wild gifts;
Boy:
Public classBoy {PrivateString name; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public voidpursue (mm mm) {Gift g=NewRing (); Give (g, mm); } Public voidgive (Gift g, mm mm) {}}
View Code
Mm
Public class MM { private String name; Public String GetName () { return name; } Public void setName (String name) { this. Name = name; } }
View Code
Some of the other gift classes are inherited from gift:
Public class Gift {} Public class extends gift{} Public class extends gift{} Public class extends gift{} Public class extends gift{}
View Code
Gift in the extension of the subclass, the extension type, it will have two dimensions of the extension;
One is the specific dimension, such as the ring is a type of division, such as warm, wild, such as now there is a gentle flower, how to organize, one way is inherited from the flower, for the warmflower; Be careful with inheritance, because the inheritance relationship represents a very strong coupling relationship, the parent class will change, the subclass will change immediately, and the design of high cohesion and low coupling; Can you find a way to support extensions on both of these dimensions? --Bridging mode:2. Bridging Mode IntroductionUse aggregation instead of inheritance; the specific implementation class of the gift, Giftimpl.java:
/**@author */public class extends gift{}
Gift:
Public class Gift { protected Giftimpl impl;}
Flower:
Public class extends giftimpl{}
View Code
Ring
Public class extends giftimpl{ }
View Code
Warmgift:
Public class extends gift{ public warmgift (Giftimpl impl) { this. Impl= impl; } }
Wildgift:
Public class extends gift{ public wildgift (Giftimpl impl) { this. Impl= impl; }}
View Code
Boy:
Public classBoy {PrivateString name; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public voidpursue (mm mm) {//Gift g = new Warmgift (new Flower ()); //The warm FlowersGift g =NewWildgift (NewRing ());//The Wild ringgive (g, mm); } Public voidgive (Gift g, mm mm) {}}
View Code
Feel a bit around, need to carefully understand the next ....
3. Summary:
If there are two dimensions in the extension of the subclass, then this time want to decouple, to solve their permutation of the problem, this time can be bridged, bridging mode is not a lot of use;
Java design mode-bridging mode