工厂模式
1.简单工厂模式
又叫静态工厂方法模式,他定义一个具体的工厂类负责创建一些类的实例
优弊:
客户端不需要在负责对象的创建,从而明确各个类的职责
如果新的对象需要创建,或创建方式不同,就需要不断的修改工厂类,不利于维护
//创建工厂类
public class beanFactory {
public class beanFactory {
public static Animal CreatAnimal(String name) {
if("dog".equals(name)){
return new Dog();
}else if("cat".equals(name )){
return new Cat();
}
return null;
}
}
if("dog".equals(name)){
return new Dog();
}else if("cat".equals(name )){
return new Cat();
}
return null;
}
}
//创建抽象类Animal
abstract class Animal {
public abstract void eat();
}
abstract class Animal {
public abstract void eat();
}
//创建Dog类继承Animal重写eat()方法
class Dog extends Animal{
@Override
public void eat() {
System.out.println("狗吃肉");
}
}
//创建Cat类继承Animal重写eat()方法
class Cat extends Animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
class Test{
public static void main(String[] args) {
Dog dog = (Dog) beanFactory.CreatAnimal("dog");
dog.eat();
Cat cat=(Cat)beanFactory.CreatAnimal("cat");
cat.eat();
}
}
public static void main(String[] args) {
Dog dog = (Dog) beanFactory.CreatAnimal("dog");
dog.eat();
Cat cat=(Cat)beanFactory.CreatAnimal("cat");
cat.eat();
}
}
2工厂方法模式
工厂方法模式中抽象工厂类负责定义定义创建对象的接口,具体对象的创建由继承抽象工厂的具体类实现
优弊
客户端不需要再负责对象的创建,从而明确了各个类的职责,如果有新的对象添加,只需要添加具体的类和具体的工厂类,增强代码的扩展性。
需要额外的编写代码,加大工作量。
//工厂接口
public interface BeanFactory {
public abstract Animal creatAnimal();
}
public interface BeanFactory {
public abstract Animal creatAnimal();
}
//创建抽象类Animal
abstract class Animal {
public abstract void eat();
}
abstract class Animal {
public abstract void eat();
}
// 创建Dog类继承Animal重写eat()方法
class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}
class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}
// 创建Cat类继承Animal重写eat()方法
class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
class DogFactory implements BeanFactory{
@Override
public Animal creatAnimal() {
// TODO Auto-generated method stub
return new Dog();
}
}
@Override
public Animal creatAnimal() {
// TODO Auto-generated method stub
return new Dog();
}
}
class catFactort implements BeanFactory{
@Override
public Animal creatAnimal() {
// TODO Auto-generated method stub
return new Cat();
}
}
public Animal creatAnimal() {
// TODO Auto-generated method stub
return new Cat();
}
}
class Test{
public static void main(String[] args) {
DogFactory dogFactory = new DogFactory();
Dog dog=(Dog) dogFactory.creatAnimal();
dog.eat();
}
}
public static void main(String[] args) {
DogFactory dogFactory = new DogFactory();
Dog dog=(Dog) dogFactory.creatAnimal();
dog.eat();
}
}