Factory method pattern -- the pattern of creation pattern

1. general factory mode

The directory structure is roughly as follows:

 

1. Create a game interface:

public interface PlayGame {
    public void game(); 
}

2. The game is implemented by two devices

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. Create a game factory

/**
 * Play game factory
 * @author Drowned fish o0
 */
public class PlayGameFactory {

    public PlayGame produce(String type){
        if ("phone".equals(type)) {  
            return new Phone();  
        } else if ("computer".equals(type)) {  
            return new Computer();  
        } else {  
            System.err.println("Please input game device!");  
            return null;  
        }  
    }
}

4. Test:

public class PlayGameTest {
    @Test
    public void gameTest() {
        PlayGameFactory factory = new PlayGameFactory();
        //PlayGame game = factory.produce("computer");
        //game.game();
        PlayGame game = factory.produce("phone");
        game.game();
    }
}

 

5. Output

 

2. Multiple factory method mode is the improvement of common factory method mode

 

Modify the above code as follows

/**
 * Play game factory
 * 
 * @author Drowned fish o0
 */
public class PlayGameFactory {
    public PlayGame producePhone() {
        return new Phone();
    }

    public PlayGame produceComputer() {
        return new Computer();
    }
}

Test:

public class PlayGameTest {
    @Test
    public void gameTest() {
        PlayGameFactory factory = new PlayGameFactory();
        PlayGame game = factory.producePhone();
        game.game();
    }
}

 

3. Static factory method mode

    

/**
 * Play game factory
 * 
 * @author Drowned fish o0
 */
public class PlayGameFactory {
    public static PlayGame producePhone() {
        return new Phone();
    }

    public static PlayGame produceComputer() {
        return new Computer();
    }
}

 

Summary: factory pattern is suitable for creating objects quickly

 

Welcome to reprint:

Chinese Name: Huifan

Blog name: drowned fish o0

Please indicate the source of Reprint: http://www.cnblogs.com/huifan/

Keywords: Java Mobile

Added by Monkey-Moejo on Sun, 03 May 2020 20:08:50 +0300