Analytics

顯示具有 Object-Oriented 標籤的文章。 顯示所有文章
顯示具有 Object-Oriented 標籤的文章。 顯示所有文章

2013年4月1日 星期一

[Design Pattern]Creational Pattern-Factory Method Design Pattern

使用時機:
需要高度靈活性,簡單擴展子類別.
例如:
有多個地區生產各種水果,盤商只須對供應商下訂單,不須了解供應商接單後,水果從哪個地區出貨!但重點是皆能取得下訂商品!
使用方式:
class  FactoryPattern 
{
interface IProduct {
string ShipFrom( );
}
class ProductA : IProduct
{
public String ShipFrom ( ) {
return " from South Africa";
}
}
class ProductB : IProduct
{
public String ShipFrom ( ) {
return "from Spain";
}
}
class DefaultProduct : IProduct
{
public String ShipFrom ( ) {
return "not available";
}
}

class Creator
{
public IProduct FactoryMethod(int month)
{
if (month  >= 4 && month <=11)
return new ProductA( );
else
{
if (month  ==  1  || month  ==  2  || month  ==  12)return new ProductB( );
}
else return new  DefaultProduct( );
}
}
以上面的例子來說:
IProduct 介面是出貨地區,ProductA,ProductB都會出貨,而從哪出貨是由Creator 類別由月份決定以彈性出貨,使用者下訂單時,只需對Creator 類別下單即可
Creator c = new Creator( );

IProduct product;
product  =  c.FactoryMethod(i);
product.ShipFrom();
參考書籍c#3.0 design pattern

[Design Pattern]Structural Pattern-Façade Design Pattern

使用時機:
對使用者提供簡單的操作行為,程式內部卻可能是集合多個子系統進行複雜的運算動作.
例如:
購物網站上的購物車,當使用者登入後,在商品上輕鬆的點選加入購物車,就可以進行記錄甚至直接進行結帳動作!這對使用者僅是簡單的點擊行為,對購物網站的系統卻是經由使用者的登入進行身分驗證,在經由驗證後行為取得個人信用資料進行購物交易等複雜動作,而使用者卻不需理會!
使用方式:
namespace Library
{
internal class SubsystemA {
internal string A1( )
{
return "Subsystem A, Method A1\n";
}
internal string A2( )
{
return "Subsystem A, Method A2\n";
}
}
internal class SubsystemB
{
internal string B1( )
{
return "Subsystem B, Method B1\n";
}
}
internal class SubsystemC
{
internal string C1( )
{
return "Subsystem C, Method C1\n";
}
}
}

public static class Facade
{
static SubsystemA a = new SubsystemA( );
static SubsystemB b = new SubsystemB( );
static SubsystemC c = new SubsystemC( );
public static void Operation1( )
{
Console.WriteLine("Operation 1\n" +a.A1( ) +a.A2( ) + b.B1( ));
}
public static void Operation2( )
{
Console.WriteLine("Operation 2\n" +b.B1( ) + c.C1( ));
}
}

以上面的例子來說:
使用namespace去包裝數個子系統,而使用Facade class作整合,並提供對外操作,而使用者是無法直接存取子系統的!
Facade.Operation1( );
Facade.Operation2( );

參考書籍c#3.0 design pattern

[Design Pattern]Structural Pattern-Adapter Design Pattern(配適模式)

使用時機:
舊有程式需增加功能或行為,而不需重寫或變動舊有程式,使用者統一透過interface存取新程式.
例如:Mac OS可執行本身PowerPC Process指令集也可執行不同指令集的windows(intel sse),也就是在Mac OS底下可以執行Windows,讓新舊程式可共存.
使用方式:
class Adaptee
{
// Provide full precision
public double SpecificRequest (double a, double b)
{
return a/b;
}
}
// Required standard for requests
interface ITarget
{
// Rough estimate required
string Request (int i);
}
// Implementing the required standard via Adaptee
class Adapter : Adaptee, ITarget
{
public string Request (int i)
{
return "Rough estimate is " + (int) Math.Round(SpecificRequest (i,3));
}
}

以上面的例子來說:
舊有的程式使用如下方式叫用,結果如下:

Adaptee  first =  new  Adaptee( );
first.SpecificRequest(5,3);

結果:1.66666666666667
新的程式使用如下方式叫用,結果如下:

ITarget second = new Adapter( );
second.Request(5);
結果:2

參考書籍c#3.0 design pattern

2013年3月29日 星期五

[Design Pattern]Structural Pattern-Composite Design Pattern(綜合模式)

使用時機:
不同物件卻須集合在一起控制.
例如:資料夾裡面除了放圖片以外,還可以放excel,電影檔,跟圖片,而在資料夾內,又可以放入新的物件,或是移除等動作
實作方面就需要用到泛型與物件屬性,這是.Net Framework 3.0含以上的版本才有
使用方式:
namespace CompositePattern {
// The Interface
public interface IComponent <T>
{
void Add(IComponent <T> c);
IComponent <T> Remove(T s);
IComponent <T> Find(T s);
T Name {get; set;}
}
// The Component
public class Component <T> : IComponent <T>
{
public T  Name  {get; set;}
public Component (T name)  
{
Name  =  name;
}
public void Add(IComponent <T> c)
{
Console.WriteLine("Cannot add to an item");
}
public IComponent <T>  Remove(T s)
{
Console.WriteLine("Cannot remove directly");
return this;
}
public IComponent <T>   Find (T s)
{
if (s.Equals(Name))
return this;
else
return null;
}
}
// The  Composite
public class Composite <T> : IComponent <T>
{
List<IComponent <T>> list;
public T  Name  {get; set;}
public Composite (T name)
{
Name  =  name;
list =  new List <IComponent  <T>> ( );
}
public void Add(IComponent  <T> c)
{
list.Add(c);
}
IComponent  <T>  holder=null;
// Finds the item from a particular point in the structure// and returns the composite from which it was removed// If not found, return the point as given
public IComponent <T> Remove(T s)
{
holder = this;
IComponent <T> p = holder.Find(s);
if (holder!=null)
{
return holder;
}
else
return this;
(holder  as  Composite<T>).list.Remove(p);
}
// Recursively looks for an item// Returns its reference or else null
public IComponent <T>   Find (T s)
{
holder = this;
if (Name.Equals(s)) return this;
IComponent <T> found=null;
foreach (IComponent <T> c in list)
{
found = c.Find(s);
if (found!=null)
break;
}return found;
}
}
}
以上面的例子來說:
使用IComponent <T> 泛型介面,提供任一型別皆可繼承
實作Component <T>物件,透過繼承IComponent <T>泛型介面來實作並提供物件本身可供外部存取,注意的是(物件本身不對自己做Add(),Remove()動作,是由外部容器提供)
實作Composite <T>物件,透過繼承IComponent <T>泛型介面來實作並提供物件本身可供外部存取,注意的是(物件本身對Component <T>做Add(),Remove()動作)
而外部存取時,使用方式如下

IComponent <string> album = new Composite<string>("Album");
Image img1 = new Image();
album.Add(new Component<Image>(img1 ));
album.Find(img1 );
參考書籍c#3.0 design pattern

[Design Pattern]Structural Pattern-Bridge Design Pattern(橋接模式)

使用時機:
實現低耦合,物件間可以切換且彼此獨立存在.
系統中功能各自獨立且須獨立開發時,可使用此方式統一調用,但各自獨立.
例如:.NetFramework各版本可以獨立存在,且使用時須指定使用的版本或路徑
使用方式:
class BridgePattern
{
class Abstraction
{
IBridge bridge;
public  Abstraction  (IBridge implementation)
{
bridge  =  implementation;
}
public string Operation ( ) {
return "Abstraction <<< BRIDGE >>>> "+bridge.OperationImp( );
}
}
interface IBridge
{
string OperationImp( );
}
class ImplementationA : IBridge
{
public string   OperationImp ( )
{
return  "ImplementationA";
}
}
class ImplementationB : IBridge
{
public string OperationImp ( )
{
return  "ImplementationB";
}
}
}
以上面的例子來說:
使用 Abstraction class作橋接,由其中的Operation ( )來判斷叫用物件
當各物件透過繼承IBridge 介面時,統一對外的動作
也就是說外部存取時,可以同時存在ImplementationA ,ImplementationB且調用時使用指定物件方式個物件不會互相干擾
而外部存取時,使用方式如下
new  Abstraction  (new  ImplementationA( ).Operation( ));
new  Abstraction  (new  ImplementationB( ).Operation( ));
參考書籍c#3.0 design pattern

[Design Pattern]Structural Pattern-Proxy Design Pattern(代理模式)

使用時機:
大多使用在避免未經授權,認證就對目標物件進行存取,如此一來避免資源的浪費,也對於使用者權限範圍限制.

例如:
Facebook須登入後,才會依登入的使用者身分,給予該使用者有限的資訊擷取
class SubjectAccessor
{
public interface ISubject
{
string Request ( );
}
private class Subject
{
public string Request( )
{
return "Subject Request " + "Choose left door\n";
}
}
public class ProtectionProxy : ISubject
{
// An authentication proxy first asks for a password
Subject subject;
string password = "12345";
public string Authenticate (string supplied)
{
if (supplied!=password)
return "Protection Proxy: No access";
else
subject = new Subject( );
return  "Protection  Proxy:  Authenticated";
}
public string Request( )
{
if (subject==null)
return "Protection Proxy: Authenticate first";
else
return "Protection Proxy: Call to "+subject.Request( );
}
}
}
以上面的例子來說:
目標是要存取Subject class的物件
而要對外提供存取subject物件使用了ISubject 介面,並指定公開Request()給外部存取
為了要提供授權機制,加入了ProtectionProxy class(Proxy Pattern),並繼承ISubject實作Request(),而在讓外部存取Request()之前,要求要透過Authenticate()認證後,才實體化Subject給外部存取
而外部存取時,使用方式如下
ProtectionProxy subject = new ProtectionProxy( );
(subject  as  ProtectionProxy).Authenticate("12345");
subject.Request( );
參考書籍c#3.0 design pattern

[Design Pattern]Structural Pattern-Decorator Design Pattern(裝飾模式)

使用時機:
使用在擴充,或增加物件的行為時使用,好處是可以不更動現有物件,就可以加入新的行為.

例如:
在現有的物件上,新的物件繼承在現有的物件上並為新物件增加行為
使用方式:
public class Component
{
public string GetComponentName()
{
return "i am ori component";
}
}

public class DecoratorChild : Component
{
public string AddMethod()
{
return "call parent component :"+GetComponentName();
}
}
此時呼叫DecoratorChild的AddMethod()時,會傳回訊息
call parent component :i am ori component

也就是雖然DecoratorChild未有GetComponentName()的行為,但透過繼承後,可以不須變更原本物件,就為原本物件加上新的行為


2012年11月13日 星期二

[Design Pattern]Creational Pattern-Singleton Design Pattern(唯一模式)

使用時機:
使用在必須確保物間的唯一性,例如:多個物件共用一個Connection物件以減少Server的負載,或確保Connection物件的唯一性
使用方式:
下方程式碼設計為當外部存取SingleTon Class的Instance屬性時,會傳回已存在的實體
public sealed class SingleTon

{

 private static SingleTon _instance = null;

 // Made default constructor as private

 private SingleTon()

 {

 }

 /// <summary>

 /// Single Instance

 /// </summary>

 public static SingleTon Instance

 {

  get

  {

  lock (_instance)

  {

  _instance = _instance ?? new SingleTon();

  return _instance;

  }

 }

}

# region Rest of Implementation Logic

//Add As many method u want here as instance member.No need to make them static

# endregion

}

c#程式碼參考來源:http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp.aspx

[Design Pattern]Design Pattern導讀(Introduction to Design Pattern)

Design Pattern是軟體開發前輩所嘔心瀝血,在於他們的軟體開發生捱中所累積出來的經驗的濃縮精華,若能熟悉其應用方式,便可幫助在軟體開發的生命週期裡,減少大量因設計上缺陷所造成後續維護困難!
Design Pattern大致上分類如下:
提供有效的管理,產生與操作物件方式
提供如何設計易懂,易維護,耦合度低的物件結構
  • Behavioral Pattern:
提供如何設計物件間的互動行為
然而你會發現,大部分的系統裡,往往使用超過1個以上的Pattern混用,所以了解每個Pattern後就可以在適時的找出最佳方案

以上分類的Pattern裡包含更細項的設計方式,之後會慢慢補上,所以當在軟體開發過程中若有了Design Pattern的概念,就可以知道該看哪一部分的Pattern做參考!

2010年5月28日 星期五

物件導向(Object-Oriented)使用時機?非得用嗎?


問題

使用時機?非得用嗎?



解決方法

Object-Oriented以下簡稱OO


寫程式一段時間,才對OO有一些自己的看法,可以在這分享一下!

物件導向概念
先簡單舉例說一下OO的概念
想像一下到7-11買純喫茶,您會做什麼事?
大概就差不多就是 拿到櫃檯,付錢,拿走純喫茶
那對收銀員來說,就是 收錢,找錢  全部大概就這些動作吧!

那在寫程式的時候,就會分為以上5個動作
拿到櫃檯=>收銀員收錢=>付錢=>收銀員找錢=>拿走純喫茶

而如果一寫個相關的系統,每一個動作可當做一個物件或是FUNCTION來用
如此一來,程式碼的邏輯會更簡潔,更容易理解!

說到這,寫點CODE來嚇嚇人好了!當然,這些CODE只是示意而已!

private void main()
{
    //拿產品到櫃檯
    int getprice= price("純喫茶")
    //收銀員跟您收錢
    Message.show("您好"+ getprice+"圓")
    //付錢
    int youpayprice=100//你掏出100圓
    int getreturnprice=GetReturnPriceBack(getprice, youpayprice)
    //收銀員找錢
    Message.show("找您"+ getreturnprice +"圓")
    //拿走純喫茶
    break;
}

看到這邊,感覺不會很難懂吧!
看一下每一個物件(Function)都做些什麼事!!


//拿產品到櫃檯
private int price(int product)
{
    int price = 0
    //查出產品多少錢
    switch(product)
    {
       case "奶茶": price  =10; break;
       case "純喫茶": price = 15; break;
    }
    //傳回價錢
   return price 
}


//付錢
private int GetReturnPriceBack(string getprice, string youpayprice)
{
    //計算要找多少錢
    int GetReturnPriceBack = youpayprice-getprice

    //傳回價錢
   return GetReturnPriceBack
}

那物件導向(OO)到底有什麼好處?
這樣好了,好處在哪要有比較才知道,所以下面的程式是"非"物件導向的方式顯示,看一下是否您能理解!!


private void main()
{
    //拿產品到櫃檯
    int price = 0
    //查出產品多少錢
    switch(product)
    {
       case "奶茶": price  =10; break;
       case "純喫茶": price = 15; break;
    }

    //收銀員跟您收錢
    Message.show("您好"+ price  +"圓")
    //付錢
    int youpayprice=100//你掏出100圓
    //計算要找多少錢
    int getreturnprice  = youpayprice-price  
    //收銀員找錢
    Message.show("找您"+ getreturnprice  +"圓")
    //拿走純喫茶
    break;
}
當把角色都放在一起以後,是否就很容易昏頭了呢??
所以,物件導向(OO)的程式邏輯可以很清晰
而想像一下,如果在進行大的系統開發,如果程式都沒有任何物件導向(OO)的觀念在裡面
那....幾千,幾萬行的程式....你該怎麼辦?...就悶著頭苦幹吧!!

而如果程式導入物件導向(OO)的觀念,當您要維護的時候,你只要知道"是在哪一個動作"
然後去找該FUNCTION修改就可以了,而不需要把全部的程式都看過後,才知道要改在哪裡

但是說回來了,非得用嗎?
其實,是要看場合的!
因為如果程式不複雜,而功能又不會被別的程式所使用的話,那就不需要使用啦!

怎麼說?
因為雖然物件導向(OO)好處很多,但在開發的時候,要考慮到如何獨立出來?重複性?等等..相關問題,因為物件的"封裝"的好不好,將會影響到該物件(FUNCTION)實用性,進而影響程式的開發時程,因為物件封裝可是要花很多心思的呢!!

先分享到這邊囉~



熱門文章