首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

java 设计模式-结合模式

2014-01-12 
java 设计模式--组合模式组成部分:Component: 为参加组合的对象声明一个公共接口, 不管是组合还是叶结点.L

java 设计模式--组合模式



组成部分:
Component: 为参加组合的对象声明一个公共接口, 不管是组合还是叶结点.
Leaf: 在组合中表示叶子结点对象,叶子结点没有子结点.
Composite: 表示参加组合的有子对象的对象, 并给出树枝购件的行为.

实例:
public abstract class FolderComponent
{
?? ?private String name;

?? ?public String getName()
?? ?{
?? ??? ?return name;
?? ?}

?? ?public void setName(final String name)
?? ?{
?? ??? ?this.name = name;
?? ?}

?? ?public FolderComponent()
?? ?{
?? ?}

?? ?public FolderComponent(final String name)
?? ?{
?? ??? ?this.name = name;
?? ?}

?? ?public abstract void add(FolderComponent component);

?? ?public abstract void remove(FolderComponent component);

?? ?public abstract void display();
}

public class FileLeaf extends FolderComponent
{
?? ?public FileLeaf(final String name)
?? ?{
?? ??? ?super(name);
?? ?}

?? ?@Override
?? ?public void add(final FolderComponent component)
?? ?{
?? ??? ?//...
?? ?}

?? ?@Override
?? ?public void remove(final FolderComponent component)
?? ?{
?? ??? ?//...
?? ?}

?? ?@Override
?? ?public void display()
?? ?{
?? ??? ?System.out.println("FileLeaf:" + this.getName());
?? ?}
}

public class FolderComposite extends FolderComponent
{
?? ?private final List<FolderComponent> components;

?? ?public FolderComposite(final String name)
?? ?{
?? ??? ?super(name);
?? ??? ?this.components = new ArrayList<FolderComponent>();
?? ?}

?? ?public FolderComposite()
?? ?{
?? ??? ?this.components = new ArrayList<FolderComponent>();
?? ?}

?? ?@Override
?? ?public void add(final FolderComponent component)
?? ?{
?? ??? ?this.components.add(component);
?? ?}

?? ?@Override
?? ?public void remove(final FolderComponent component)
?? ?{
?? ??? ?this.components.remove(component);
?? ?}

?? ?@Override
?? ?public void display()
?? ?{
?? ??? ?System.out.println("FolderComposite---name:" + this.getName());
?? ??? ?for (final FolderComponent component : components)
?? ??? ?{
?? ??? ??? ?System.out.println("FolderComposite---component-name:" + component.getName());
?? ??? ?}
?? ?}
}

public class Client
{
?? ?public static void main(final String[] args)
?? ?{
?? ??? ?final FolderComponent leaf = new FileLeaf("runnable file");
?? ??? ?leaf.display();

?? ??? ?final FolderComponent folder = new FolderComposite("new folder");
?? ??? ?folder.add(new FileLeaf("content1 in new folder"));
?? ??? ?folder.add(new FileLeaf("content2 in new folder"));
?? ??? ?folder.display();
?? ?}
}

结果:
FileLeaf:runnable file
FolderComposite---name:new folder
FolderComposite---component-name:content1 in new folder
FolderComposite---component-name:content2 in new folder

热点排行