相必大家对设计模式听得比较多,可是究竟怎么运用可能大家还有点糊涂!
其实我认为gof23中设计模式就是4种,:第一种:接口作为参数传递,是传递实现了这个接口的对象
第二种:接口作为参数返回是返回这个接口的对象
第三种:抽象类作为参数传递是传递实现了这个抽象类的对象
第四种:抽象类作为参数返回是返回这个抽象类的对象
好了,不多说了,进行我们的第一种设计模式:抽象工厂模式:
需求图片说明:![](https://images.cnblogs.com/cnblogs_com/peteryao/abstractfactory.png)
AbstractFactory
public interface IAnimalFactory {
ICat createCat();
IDog createDog();
}
ConcreteFactory
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public class BlackAnimalFactory implements IAnimalFactory {
public ICat createCat() {
return new BlackCat();
}
public IDog createDog() {
return new BlackDog();
}
}
public class WhiteAnimalFactory implements IAnimalFactory {
public ICat createCat() {
return new WhiteCat();
}
public IDog createDog() {
return new WhiteDog();
}
}
AbstractProduct
public interface ICat {
void eat();
}
public interface IDog {
void eat();
}
ConcreteProduct
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public class BlackCat implements ICat {
public void eat() {
System.out.println("The black cat is eating!");
}
}
public class WhiteCat implements ICat {
public void eat() {
System.out.println("The white cat is eating!");
}
}
public class BlackDog implements IDog {
public void eat() {
System.out.println("The black dog is eating");
}
}
public class WhiteDog implements IDog {
public void eat() {
System.out.println("The white dog is eating!");
}
}
Client
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public static void main(String[] args) {
IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
ICat blackCat = blackAnimalFactory.createCat();
blackCat.eat();
IDog blackDog = blackAnimalFactory.createDog();
blackDog.eat();
IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
ICat whiteCat = whiteAnimalFactory.createCat();
whiteCat.eat();
IDog whiteDog = whiteAnimalFactory.createDog();
whiteDog.eat();
}
result
The black cat is eating!
The black dog is eating!
The white cat is eating!
The white dog is eating!