Abstract factory pattern
Package structure as shown in the figure
ps: it's a little abstract to understand
1. Function interface PlayGame.java
public interface PlayGame { public void game(); }
2. Two kinds of devices, Computer.java and Phone.java, to realize the function interface
public class Computer implements PlayGame{
@Override public void game() { System.err.println("Play computer games!!"); } }
public class Phone implements PlayGame { @Override public void game() { System.err.println("Play mobile games"); } }
3. Factory interface FactoryTypeInterface.java
public interface FactoryTypeInterface { public PlayGame playGameType(); }
4. Two kinds of factories: ComputerPlayGameFactory.java and PhonePlayGameFactory.java
ps: both factories implement the factory interface in the same way with different implementation contents
/** * factory * @author Drowned fish o0 */ public class ComputerPlayGameFactory implements FactoryTypeInterface { @Override public PlayGame playGameType() { // TODO Auto-generated method stub return new Computer(); } } /** * Game Factory * * @author Drowned fish o0 */ public class PhonePlayGameFactory implements FactoryTypeInterface{ @Override public PlayGame playGameType() { // TODO Auto-generated method stub return new Phone(); } }
5. Test:
public class PlayGameTest { @Test public void phonePlayGameTest() { FactoryTypeInterface typeInterface = new PhonePlayGameFactory(); typeInterface.playGameType().game(); } @Test public void computerPlayGameTest() { FactoryTypeInterface typeInterface = new ComputerPlayGameFactory(); typeInterface.playGameType().game(); } }
6. Test results display
7. Summary
Abstract factory is a further upgrade on the common factory. It is superior to the common factory in that when we need to add new equipment, we only need to create a new factory to implement the factory interface, which has better expansion performance
Welcome to reprint:
Chinese Name: Huifan
Blog name: drowned fish o0
When reprinting, please indicate the source: http://www.cnblogs.com/huifan/