Csdn not in the mobile network, the recent mobile campus network is not on the CSDN, today finally can board, the grass Bird wrote the recent learning design mode.
Factory estimates are almost the most used, for factory methods and abstract factory is easier to mix, the author here to say their own learning some understanding.
Factory mode:
Products
For the factory, of course, the production of products, of course, we have to have a product class, in order to expand well, first define a product interface
Public interface Animal {public void print ();
With the product interface, then of course the product
Product: Cat
public class Cat implements animal{public void print () {System.out.println ("You are a cat Oh");}}
Product: Chicken
public class Chicken implements animal{public void print () {System.out.println ("You are chicken Oh");}}
Product: Pig
public class Pig implements animal{public void print () {System.out.println ("You are a pig Oh");}
Factory
Haha, our products have, below we can not put them all where, of course, we have to produce them
The following defines a factory interface, just for the sake of extensibility well
public interface Produce{public Animal produceanimal ();}
Factory interfaces are there, of course we have to have a specific factory to produce these products
Factory: Cat
public class Factory_cat implements Produce{public Animal Produceanimal () {return new Cat ();}}
Factory: Chicken
public class Factory_chicken implements produce {public Animal produceanimal () {return new Chicken ();}}
Factory: Pig
public class Factory_pig implements produce {public Animal produceanimal () {return new Pig ();}}
Haha, the factory has, the product also has, and the factory also produced the need of products. And here's what we're going to test.
public class Test {public void Test () {Produce cat = new Factory_cat (); Cat.produceanimal (). print (); Produce chicken = new Factory_chicken (); Chicken.produceanimal (). print (); Produce pig = new Factory_pig ();p ig.produceanimal (). print (); public static void Main (string[] args) {test test = new Test (); Test.test ();}}
Write here, people will inevitably find some problems, here can only produce animals, but I want to produce pork, chicken, so how to do?
Bing go! Some people might say that I can build meat on a meat interface, which of course solves the problem, but adds another factory method,
But what if there are a lot of similar types that need to be produced? We will have a lot of factories, we may be disoriented, haha, the solution came,
It's our abstract factory. First here, the net is broken, tomorrow to make up
Factory method and Abstract factory