Design mode - use of old talks

xiaoxiao2021-03-06  41

Design mode - use of old talks

Author: janes factory pattern we are very familiar, including the commonly used simple factory, factory method and abstract factory several. In general, you should define this: Define a generic interface to create an object. Whether it is using which plant mode is the same, "Separate the process of creating objects and the use of objects to make it free to change without interaction." Using factory modes can avoid using keyword NEWs in the program, from an interface or an abstract angle, New operations should definitely avoid using them directly in the class of business logic. Because the "parameter" required after the New operation is the specific class of Type, not the abstraction (base class, or interface) of the class, this does not conform to the abstract principle. Let's take a specific example: public interface vehicle {void run ();} public class car: vehicle {public void run () {console.write ("car 's run");}} public class plane: vehicle { Public void Run () {Console.write ("Plane 'S Run");}} PUBLIC CLASS TRAIN: VEHICLE {Public Void Run () {Console.Write ("Trani' S Run");}} public class businessrole { PRIVATE VEHICLE M_VEHICLE; Public BusinessRole () {// Note Here M_VEHICLE = New Car (); or: M_VEHICLE = New Plane (); m_vehicle = new train ()} public void doexec () {Console.write ("BusinessRole 'S Exec "); vehicle.run ();}} This is the client-class public class client {businessrole obj = new businessrole () obj.doexec ();} analyzed that the above code will find that if you change the use of vehicle way You need to change the code in your businessrole directly, and the code of the Client end is not affected. But although in BusinessRole defines the field M_VEHICLE to the interface type of VEHICLE, it does not actually give us too much benefits, because each change in the type of transportation needs to change the business code in class businessrole. I have checked the previously have discovered a lot of "problem" code like this. In fact, this problem solves very simple as long as any plant method (the factory method of choosing the different choices according to the actual situation) will replace the New operation in BusinessRole to replace it. Your text expresss the words unclear, or use code to explain the problem. Define a VehicleFactory class factory to unify the subclass of the VEHICLE, and then call the businessrole to create an instance of a VEHICLE.

转载请注明原文地址:https://www.9cbs.com/read-55277.html

New Post(0)