工厂模式
1、工厂模式定义
工厂模式是java中最常用的设计模式之一。这种设计模式属于创建型模式,他提供了一种创建对象的最佳方式
在工厂模式中,我们在创建对象是不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象
通过工厂模式,将创建对象的实例的权利移交工厂,我们不在通过new来创建我们所需的对象,而是通过工厂来获取我们需要的产品。降低了产品和使用这之间的耦合关系
2、工厂模式
public interface Phone {
void make();
}
public class MiPhone implements Phone {
public MiPhone() {
this.make();
}
@Override
public void make() {
System.out.println("生产小米");
}
}
public class HuaWeiPhone implements Phone {
public HuaWeiPhone() {
this.make();
}
@Override
public void make() {
System.out.println("生产华为");
}
}
2.1简单工厂模式
public class PhoneFactory{
public Phone makePhone(String phoneType){
if (phoneType.equals("HuaWeiPhone")){
return new HuaWeiPhone();
}else if (phoneType.equals("MiPhone")){
return new MiPhone();
}
return null;
}
}
public class Test{
public static void main(String[] args) {
PhoneFactory phoneFactory = new PhoneFactory();
Phone huaWeiPhone = phoneFactory.makePhone("HuaWeiPhone");
Phone miPhone = phoneFactory.makePhone("MiPhone");
}
}
2.2工厂方法模式
public interface AbstractFactory {
Phone makePhone();
}
public class HuaWeiPhoneFactory implements AbstractFactory {
@Override
public Phone makePhone() {
return new HuaWeiPhone();
}
}
public class MiFactory implements AbstractFactory {
@Override
public Phone makePhone() {
return new MiPhone();
}
}
2.3抽象工厂
public interface PC {
void makePC();
}
public class HwPC implements PC {
public HwPC(){
this.makePC();
}
@Override
public void makePC() {
System.out.println("HwPC");
}
}
public class MiPC implements PC {
public MiPC(){
this.makePC();
}
@Override
public void makePC() {
System.out.println("MiPC");
}
}
public interface AbstractFactory {
Phone makePhone();
PC makePC();
}
public class MiFactory implements AbstractFactory {
@Override
public Phone makePhone() {
return new MiPhone();
}
@Override
public PC makePC() {
return new MiPC();
}
}
public class HuaWeiPhoneFactory implements AbstractFactory {
@Override
public Phone makePhone() {
return new HuaWeiPhone();
}
@Override
public PC makePC() {
return new HwPC();
}
}
public class FactoryTest {
public static void main(String[] args) {
MiFactory miFactory = new MiFactory();
HuaWeiPhoneFactory huaWeiPhoneFactory = new HuaWeiPhoneFactory();
miFactory.makePhone();
miFactory.makePC();
huaWeiPhoneFactory.makePhone();
huaWeiPhoneFactory.makePC();
}
}