抽象工厂模式【ABSTRACT FACTORY PATTERN】 a

本文介绍了一种使用抽象工厂模式创建网页元素的方法。通过定义抽象基类Factory,并实现具体的工厂类,可以灵活地创建链接(Link)、托盘(Tray)和页面(Page)等对象。每个对象都可以生成相应的HTML代码,最终组合成完整的网页。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Vector;


public abstract class Factory
{
public static Factory getFactory(String classname)
{
Factory factory = null;
try
{
factory = (Factory)Class.forName(classname).newInstance();
}
catch (ClassNotFoundException e)
{
System.err.println(classname + e.getMessage());
}
catch (Exception e)
{
e.printStackTrace();
}
return factory;
}

public abstract Link createLink(String caption, String url);

public abstract Tray createTray(String caption);

public abstract Page createPage(String title, String author);
}


public abstract class Item
{
protected String caption;

public Item(String caption)
{
this.caption = caption;
}

public abstract String makeHTML();
}


public abstract class Link extends Item
{
protected String url;

public Link(String caption, String url)
{
super(caption);
this.url = url;
}
}



public abstract class Page {
protected String title;
protected String author;
protected Vector content = new Vector();
public Page(String title, String author) {
this.title = title;
this.author = author;
}
public void add(Item item) {
content.add(item);
}
public void output() {
try {
String filename = title + ".html";
Writer writer = new FileWriter(filename);
writer.write(this.makeHTML());
writer.close();
System.out.println(filename + " createm over");
} catch (IOException e) {
e.printStackTrace();
}
}
public abstract String makeHTML();
}



public abstract class Tray extends Item {
protected Vector tray = new Vector();
public Tray(String caption) {
super(caption);
}
public void add(Item item) {
tray.add(item);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值