工厂类
package miluo.design.patterns.simpleFactory;/*** @author Miluo* @className MachineFactory* @description 工厂类* @date 2022/2/16**/public class MachineFactory {public static Machine getMachine(String country) throws Exception {if ("cn".equals(country.toLowerCase())) {return new ChinaMachine();}else if ("usa".equals(country.toLowerCase())){return new AmericanMachine();}else {throw new Exception("请输入正确参数");}}}
抽象产品类
package miluo.design.patterns.simpleFactory;/*** @author Miluo* @className Machine* @description 抽象产品类* @date 2022/2/16**/public abstract class Machine {/*** sayHello* @return String*/public abstract String welcome();}
具体产品类
package miluo.design.patterns.simpleFactory;/*** @author Miluo* @className ChinaMachine* @description* @date 2022/2/16**/public class ChinaMachine extends Machine {@Overridepublic String welcome() {return "你好";}}
package miluo.design.patterns.simpleFactory;/*** @author Miluo* @className ChinaMachine* @description* @date 2022/2/16**/public class AmericanMachine extends Machine {@Overridepublic String welcome() {return "Hello";}}
测试
package miluo.design.patterns.simpleFactory;/*** @author Miluo* @className testSimpleFactory* @description* @date 2022/2/16**/public class TestSimpleFactory {public static void main(String[] args) {try {Machine cn = MachineFactory.getMachine("cn");System.out.println(cn.welcome());Machine usa = MachineFactory.getMachine("USA");System.out.println(usa.welcome());Machine jp = MachineFactory.getMachine("jp");System.out.println(jp.welcome());} catch (Exception e) {e.printStackTrace();}}}**********************************Connected to the target VM, address: '127.0.0.1:7163', transport: 'socket'你好Hellojava.lang.Exception: 请输入正确参数at miluo.design.patterns.simpleFactory.MachineFactory.getMachine(MachineFactory.java:16)at miluo.design.patterns.simpleFactory.TestSimpleFactory.main(TestSimpleFactory.java:16)Disconnected from the target VM, address: '127.0.0.1:7163', transport: 'socket'Process finished with exit code 0**********************************
测试
package miluo.design.patterns.factoryMethod;import miluo.design.patterns.simpleFactory.Machine;/*** @author Miluo* @className TestFactoryMethod* @description* @date 2022/2/16**/public class TestFactoryMethod {public static void main(String[] args) {CnFactory cnFactory = new CnFactory();Machine cnFactoryMachine = cnFactory.getMachine();System.out.println(cnFactoryMachine.welcome());UsaFactory usaFactory = new UsaFactory();Machine usaFactoryMachine = usaFactory.getMachine();System.out.println(usaFactoryMachine.welcome());}}***********************************Connected to the target VM, address: '127.0.0.1:7725', transport: 'socket'你好HelloDisconnected from the target VM, address: '127.0.0.1:7725', transport: 'socket'***********************************
