设计模式-----工厂模式
工厂模式,顾名思义是类似生产产品的一种设计模式,而它是根据传递进来的引用来创建相对应产品的
简单工厂模式
//手机生产标准接口
public interface Phone(){
void make();
}
//生产华为
public class HuaWei() interface Phone{
public HuaWei(){
this.make();
}
@Override
public void make (
System.out.println("生产华为手机");
)
}
//生产红米
public class HongMi() interface Phone{
public HongMi(){
this.make()
}
}
//生产手机工厂类
public class Factory(){
public Phone getPhone(String phonename){
if(phonename.equalsIgnoreCase("Huawei")){
return new HuaWei();
}
else if(phonename.equalsIgnoreCase("Hongmi")) {
return new HongMi();
}
return null;
}
}
}
//测试
public class Demo {
public static void main(String[] arg) {
Factory factory = new Factory();
Phone phone = factory.makePhone("Huawei"); //
IPhone iPhone = (IPhone)factory.makePhone("Hongmi"); //
}
}
工厂方法模式
此模式中,通过定义一个抽象的核心工厂类,并定义创建产品对象的接口,创建具体产品实例的工作延迟到其工厂子类去完成。这样做的好处是核心类只关注工厂类的接口定义,而具体的产品实例交给具体的工厂子类去创建。当系统需要新增一个产品是,无需修改现有系统代码,只需要添加一个具体产品类和其对应的工厂子类,使系统的扩展性变得很好,符合面向对象编程的开闭原则
需要将工厂类抽象出来
public interface Factory(){
public Phone get();
}
public class HuaweiFactory() interface Factory{
@Override
public Phone get(){
return new Huawei();
}
}
public class HongMiFactory() interface Factory{
@Override
public Phone get(){
return new HongMi();
}
}
public class FactoryMethodTest {
public static void main(String[] args) {
Factory factory = new HongMiTeaFactory();
factory.get();
factory = new HuaweiFactory();
factory.get();
}
}
抽象工厂
有时间了再写