Factory method Mode
Defines an interface for creating objects, letting subclasses decide which class to instantiate. The factory method defers the instantiation of a class to a subclass.
Operation class
PackageCom.hml.factory.method; Public Abstract classOperation {Private intNumbera; Private intNumberb; Public intGetnumbera () {returnNumbera; } Public voidSetnumbera (intNumbera) { This. Numbera =Numbera; } Public intGetnumberb () {returnNumberb; } Public voidSetnumberb (intNumberb) { This. Numberb =Numberb; } Public Abstract intGetResult ();}
Addoperation class
Package Com.hml.factory.method; Public class extends Operation { publicint getresult () { return Getnumbera () + Getnumberb (); }}
Suboperation class
Package Com.hml.factory.method; Public class extends Operation { publicint getresult () { return Getnumbera ()- Getnumberb (); }}
Ifactory class
Package Com.hml.factory.method; Public Interface ifactory { public Operation CreateOperation ();}
Addoperationfacotry class
Package Com.hml.factory.method; Public class Implements ifactory { public Operation CreateOperation () { returnnew addoperation (); }}
Package Com.hml.factory.method; Public class Implements ifactory { public Operation CreateOperation () { returnnew suboperation (); }}
Class diagram
When the factory method pattern is implemented, the client needs to decide which factory to instantiate to implement the Operation class, the problem of choosing judgment is still there, that is, the factory method moves the internal logic judgment of the simple factory to the client code, wants to add the function, it is to modify the factory class, and now is to modify the client code.
Factory method Pattern of design pattern