- Simple Factory mode
As an example:
Small z likes to eat fruit (Fruit) more like to drink juice (juice), like three kinds of fruit melon (hami melon), banana (banana), peach (peach) use simple factory to achieve small Z drink Juice dream
Uml
First choose fruit (Fruit):
/*
* A way to get fruit and get a juice squeeze
*/
Public interface Fruit {
public void Getjuice ();
}
Cantaloupe:
/*
* Fruit juice function is realized with cantaloupe
*/
public class Hamimelon implements Fruit {
@Override
public void Getjuice () {
System.out.println ("Hamimelon Juice");
}
}
Banana:
/*
* Fruit juice function with banana
*/
public class Banana implements Fruit {
@Override
public void Getjuice () {
System.out.println ("Banana Juice");
}
}
Peach:
/*
* Fruit juice function with peach
*/
public class Peach implements Fruit {
@Override
public void Getjuice () {
System.out.println ("Peach Juice");
}
}
Processing plant:
Package simplefactory;
/*
* This fruit processing plant is to squeeze fruit into juice
*/
public class Fruitfactory {
Public Fruit createjuice (int choose) {
Switch to select the appropriate juice flavor
System.out.println ("1 Peachjuice 2 Hamimelon 3 Banana");
Switch (choose) {
Case 1:
return new Peach ();
Case 2:
return new Hamimelon ();
Case 3:
return new Banana ();
}
return null;
}
}
Test class:
Test program
public class Testdemo {
public static void Main (string[] args) {
Fruitfactory ff = new Fruitfactory ();
Fruit f = ff.createjuice (1);
F.getjuice ();
}
}
Output:
1 Peachjuice 2 Hamimelon 3 Banana
Peach Juice
2. Factory method
Small Z is a kind of juice under the distinction of a phase so
Design Patterns Simple Factory, factory method, abstract factory