雷锋依然在人间——工厂方法模式

雷锋依然在人间——工厂方法模式

工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

工厂方法模式结构图
//雷锋

public class LeiFeng {
public void Sweep() {
    System.out.println("扫地");
}

public void Wash() {
    System.out.println("洗衣");
}

public void BuyRice() {
    System.out.println("买米");
}
}

//学雷锋的大学生类,继承雷锋

public class Undergraduate extends LeiFeng{
}

//社区志愿者

public class Volunteer extends LeiFeng {
}

//雷锋工厂

public interface IFactory {
LeiFeng createLeiFeng();
}

//学雷锋的大学生工厂

public class UndergraduateFactory implements IFactory {
public LeiFeng createLeiFeng() {
    return new Undergraduate();
}
}

//社区志愿者工厂

public class VolunteerFactory implements IFactory {
public LeiFeng CreateLeiFeng() {
    return new Volunteer();
}

@Override
public LeiFeng createLeiFeng() {
    return null;
}
}

//主函数

public class Main {
public static void main(String[] args) {
    IFactory factory = new UndergraduateFactory();
    LeiFeng student = factory.createLeiFeng();

    student.BuyRice();
    student.Sweep();
    student.Wash();
}
}

工厂方法模式克服了简单工厂违背开放-封闭原则的缺点,又保持了封闭对象创建过程的优点。它们都是集中封闭了对象的创建,使得要更换对象时,不需要做大的改动就可以实现,降低客户程序与产品对象的耦合。工厂方法模式是简单工厂模式的进一步抽象和推广。由于使用了多态性,工厂方法模式保持了简单工厂模式的优点,而且克服了它的缺点。但缺点是由于每加一个产品,就需要加一个产品工厂的类,增加了额外的开发量,还是没有避免修改客户端的代码。不过利用‘反射’可以解决避免分支判断的问题。

利用java语言开发建议日历记事本程序。 public class CalendarPad extends JFrame implements MouseListener{ int year,month,day; Hashtable hashtable; File file; static JTextField showDay[]; JLabel title[]; Calendar calendar; int week; NotePad notepad=null; Month changemonth; Year changeyear; String 星期[]={"日","一","二","三","四","五","六"}; JPanel leftPanel,rightPanel; //以下是定义CalendarPad方法 public CalendarPad(int year,int month,int day) { super("Duang日历记事本"); //设置窗体标题 leftPanel=new JPanel(); JPanel leftCenter=new JPanel(); JPanel leftNorth=new JPanel(); leftCenter.setLayout(new GridLayout(7,7)); rightPanel=new JPanel(); this.year=year; this.month=month; this.day=day; changeyear=new Year(this); changeyear.setYear(year); changemonth=new Month(this); changemonth.setMonth(month); title=new JLabel[7]; //定义显示星期标签 showDay=new JTextField[42]; for(int j=0;j<7;j++) { title[j]=new JLabel(); title[j].setText(星期[j]); //定义显示星期标签 title[j].setBorder(BorderFactory.createRaisedBevelBorder()); //定义边框为斜面边框(凸) leftCenter.add(title[j]); //显示星期标签 } title[0].setForeground(Color.red); //将周日显示为红色 title[6].setForeground(Color.red); //将周六显示为红色 for(int i=0;i<42;i++) { showDay[i]=new JTextField(); showDay[i].addMouseListener(this); //添加鼠标进入 showDay[i].setEditable(false); //设置为不可编辑标签 leftCenter.add(showDay[i]); } calendar=Calendar.getInstance(); Box box=Box.createHorizontalBox(); box.add(changeyear); //添加改变年控件 box.add(changemonth); //添加改变月控件 leftNorth.add(box); //定位改变年月标签
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值