• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
雪飞夏日
博客园    首页    新随笔    联系   管理    订阅  订阅
AbstractFactory抽象工厂设计模式

相必大家对设计模式听得比较多,可是究竟怎么运用可能大家还有点糊涂!

其实我认为gof23中设计模式就是4种,:第一种:接口作为参数传递,是传递实现了这个接口的对象

                                                    第二种:接口作为参数返回是返回这个接口的对象

                                                    第三种:抽象类作为参数传递是传递实现了这个抽象类的对象

                                                    第四种:抽象类作为参数返回是返回这个抽象类的对象

好了,不多说了,进行我们的第一种设计模式:抽象工厂模式:

 

需求图片说明:

 

 

AbstractFactory
public interface IAnimalFactory {

    ICat createCat();
    
    IDog createDog();
}
ConcreteFactory
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
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
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!

 

posted on 2009-07-27 11:38  雪飞夏日  阅读(177)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3