工厂模式
普通工厂:
定义接口:
public interface Gong {
void add()throws Exception;
void delete()throws Exception;
}
实现类:
1
public class Gong1 implements Gong {
@Override
public void add() throws Exception {
System.out.println("添加");
}
@Override
public void delete() throws Exception {
// TODO Auto-generated method stub
System.out.println("删除");
}
}
2
public class Gong2 implements Gong {
@Override
public void add() throws Exception {
// TODO Auto-generated method stub
System.out.println("添加2");
}
@Override
public void delete() throws Exception {
// TODO Auto-generated method stub
System.out.println("删除2");
}
}
工厂类:
public class GongChang {
public String type;
public GongChang(String type){
this.type =type;
}
public Gong test(){
if(type=="gong1"){
return new Gong1();
}
if(type=="gong2"){
return new Gong2();
}
return null;
}
}
测试类:
public static void main(String[]args) throws Exception{
GongChang gongChang = new GongChang("gong1");
Gong ter = gongChang.test();
ter.add();
}
多个工厂方法模式:
只需要修改工厂类
public class GongChang1 {
public Gong gong1(){
return new Gong1();
}
public Gong gong2(){
return new Gong2();
}
}
测试类:
//多个工厂模式
GongChang1 gongChang1 = new GongChang1();
Gong gong =gongChang1.gong1();
gong.add();
静态工厂方法模式
修改工厂类:
public class GongChang2 {
public static Gong gong1(){
return new Gong1();
}
public static Gong gong2(){
return new Gong2();
}
}
测试类:
Gong gong =GongChang2.gong1();
gong.add();