Design Pattern factory method pattern

Source: Internet
Author: User

Design Pattern factory method pattern

Main content:

1. Factory method mode

2. Multiple factory method Modes

3. Static Method Mode

 

I. Factory method mode

 

public abstract class Animal {public abstract void eat();}

public class Cat extends Animal {@Overridepublic void eat() {}}

public class Dog extends Animal { @Override public void eat() { } }

 



package factory; public class AnimalFactory1 { public Animal createAnimal(String animal) { if (dog.equals(animal)) { return new Dog(); } if (cat.equals(animal)) { return new Cat(); } return null; } } 



 

 

Ii. Multiple factory method Modes

 

 

public class AnimalFactory2 {public Animal createDog() {return new Dog();}public Animal createCat() {return new Cat();}}


 

Iii. Static Method Mode

 

public class AnimalFactory3 {public static Animal createDog() {return new Dog();}public static Animal createCat() {return new Cat();}}

 

Iv. Test

 

@Testpublic void test1() {AnimalFactory1 factory = new AnimalFactory1();Animal a1 = factory.createAnimal(cat);Animal a2 = factory.createAnimal(dog);a1.eat();a2.eat();}@Testpublic void test2() {AnimalFactory2 factory = new AnimalFactory2();Animal a1 = factory.createCat();Animal a2 = factory.createDog();a1.eat();a2.eat();}@Testpublic void test3() {Animal a1 = AnimalFactory3.createCat();Animal a2 = AnimalFactory3.createDog();a1.eat();a2.eat();}

 

The results are the same and the code is different. It seems that the third method is better.

 

 

 

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.