What Is the Factory Pattern?

The factory pattern is our most commonly used instantiation object pattern. It is a pattern that uses factory methods instead of new operations. The famous Jive forum has made extensive use of the factory mode. The factory mode can be seen everywhere in the Java program system. Because the factory pattern is equivalent to creating new instance objects, we often need to generate instance objects based on the class Class. For example, A a = new A () The factory pattern is also used to create instance objects, so in the future new will need more attention. Whether you can consider using the factory pattern. Although doing so may do more work, it will bring greater scalability and minimal modification to your system.

Factory mode

Factory pattern definition
Let's take the class Sample as an example. If we want to create an instance of Sample:
Sample sample = new Sample ();
However, the actual situation is that usually we need to do some initialization work when creating a sample instance, such as assigning a value to query the database.
The first thing we thought of was that we could use Sample
You will build a factory that specializes in producing Sample instances:
  public class Factory {
 public static ISample creator (int which) {
 if (which == 1)
 return new SampleA ();
 else if (which == 2)
 return new SampleB ();
 }
 }
Then in your program, if you want to create a real column of ISample, you can use
ISample sampleA = Factory.creator (1);
In this way, the specific implementation class of ISample is not involved throughout.
The factory pattern has: Factory Method
  <? php
 interface abstracted {
 public function realCreate ();
 }
 // Woman class class Woman {
 public function action () {
 echo 'This is a woman';
 }
 }
 // Man class class Man {
 public function action () {
 echo 'This is a man';
 }
 }
 // Create woman class WomanCreator implements abstracted {
 public $ chromosome; // chromosome public function realCreate () {
 if ($ this-> chromosome == "xx") {
 return new Woman ();
 }
 }
 }
 // create man class ManCreator implements abstracted {
 public $ chromosome;
 public function realCreate () {
 if ($ this-> chromosome == "xy" || $ this-> chromosome == "xyy") {
 return new Man ();
 }
 }
 }
 // human factory class PersonFactory {
 public function create ($ what) {
 $ create = $ what. "Creator";
 return $ create = new $ create ();
 }
 }
 $ create = new PersonFactory ();
 $ instance = $ create-> create ('Woman');
 $ instance-> chromosome = "xx";
 $ instance-> realCreate ()-> action ();
 ?> 

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?