我正在阅读关于设计模式基础的内容,并遇到了两种基本定义:结构模式和行为模式,具体如下:
结构设计模式:通常涉及实体之间的关系,使这些实体更容易协同工作。
行为设计模式:用于实体之间的通信,并使这些实体之间的通信更加简便和灵活。
阅读这些内容后,我无法区分它们之间的区别,请有经验的人给一些最简单的示例来指导我吗?
我正在阅读关于设计模式基础的内容,并遇到了两种基本定义:结构模式和行为模式,具体如下:
结构设计模式:通常涉及实体之间的关系,使这些实体更容易协同工作。
行为设计模式:用于实体之间的通信,并使这些实体之间的通信更加简便和灵活。
阅读这些内容后,我无法区分它们之间的区别,请有经验的人给一些最简单的示例来指导我吗?
最好的解释方式是通过来自两个不同类别的例子。
结构型模式中的组合模式定义了一种类似于树形结构的关系,因此侧重于关系。它具有一对多的关系类型,从而可以将整体和部分视为相同。
另一方面,行为设计模式中的观察者模式侧重于通信。我们如何让相关方知道对象发生的任何更改。类似于发布者和订阅者。它不定义严格的结构,但强制实现方法,即通信渠道。
希望这对您有所帮助。
将行为视为与结构外部的场景有关。某些数据结构可以在多个行为/场景中“被使用”。
另一方面,将与结构相关的逻辑视为内部于结构。结构会受到各种变化的影响,并因此执行一些操作。
话虽如此,我们可以用以下示例来说明:
结构设计模式将通过定义其组成部分(例如文章/图片/评论)作为高级业务对象来定义Web日志。这些组成部分知道彼此以及如何相互连接。
$image = new Image;
$image->title = 'Image title';
$image->url = 'http://example.com/file.ext';
$image->save(); // will save the image to a DB
$article->title = 'The title i have set';
/* $article->url_key = 'the_title_i_have_set'; */
// this ^^ element of logic will be done automatically by the article
$article->addImage($image); // will save the connection between the
// article and the image to DB
行为设计模式将通过使用较低级别的业务对象(如Article / ArticleToImage / Image / ArticleToComment)定义博客的用例(场景)。这些业务对象不知道彼此,并且由场景逻辑“操纵”到其位置。
$image = new Image;
$image->title = 'Image title';
$image->url = 'http://example.com/file.ext';
$image->save(); // will save the image to a DB
$article->title = 'The title i have set';
$article->url_key = $controller->getURlKey($article->title);
$article->save(); // saves article to DB
$article_to_image = new ArticleToImage;
$article_to_image->article = $article;
$article_to_image->image = $image;
$article_to_image->save();
如果存储对象是智能的(包含逻辑),这就是结构性设计。如果存储对象是愚蠢的(只能存储数据并将其传输到数据库),则需要行为设计来管理它们。
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
using System;
namespace wildert
{
public class Metronome
{
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(Metronome m, EventArgs e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
Tick(this, e);
}
}
}
}
public class Listener
{
public void Subscribe(Metronome m)
{
m.Tick += new Metronome.TickHandler(HeardIt);
}
private void HeardIt(Metronome m, EventArgs e)
{
System.Console.WriteLine("HEARD IT");
}
}
class Test
{
static void Main()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}
}