Design Patterns Simple Factory, factory method, abstract factory

Source: Internet
Author: User

    1. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.