0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go】簡単なAbstract Factoryパターンのサンプルコード

Last updated at Posted at 2025-03-14

概要

  • Goで簡単なAbstract Factoryパターンを実装。

実装内容

  • 異なる通知方法(EmailやSMS)のインスタンスを生成し、メッセージを送信するサンプルコード
    • Notifierインターフェース: 通知を送るためのメソッドを定義
    • EmailNotifier と SMSNotifier: それぞれEmailとSMSの通知を実装
    • NotificationFactoryインターフェース: Notifierのインスタンスを生成するためのファクトリインターフェース
    • SendNotification関数: ファクトリを使って通知を送ることができる

サンプルコード

package main

// Notifier は通知を送るためのインターフェース
type Notifier interface {
	// SendNotification は通知メッセージを送信する
	SendNotification(message string) string
}

// EmailNotifier は Email 通知の実装
type EmailNotifier struct{}
func (n *EmailNotifier) SendNotification(message string) string {
	return "Email: " + message
}

// SMSNotifier は SMS 通知の実装
type SMSNotifier struct{}
func (n *SMSNotifier) SendNotification(message string) string {
	return "SMS: " + message
}

// NotificationFactory は Notifier を作成するファクトリインターフェース
type NotificationFactory interface {
	// CreateNotifier は Notifier を作成する
	CreateNotifier() Notifier
}

// EmailNotificationFactory は Email 通知のファクトリ
type EmailNotificationFactory struct{}
func (f *EmailNotificationFactory) CreateNotifier() Notifier {
	return &EmailNotifier{}
}

// SMSNotificationFactory は SMS 通知のファクトリ
type SMSNotificationFactory struct{}
func (f *SMSNotificationFactory) CreateNotifier() Notifier {
	return &SMSNotifier{}
}

// SendNotification はファクトリを使って通知を送信
func SendNotification(factory NotificationFactory, message string) string {
	notifier := factory.CreateNotifier()
	return notifier.SendNotification(message)
}

// 使用例
func main() {
	// Email 通知の送信
	emailFactory := &EmailNotificationFactory{}
	emailMessage := SendNotification(emailFactory, "Hello, Email!")
	println(emailMessage)

	// SMS 通知の送信
	smsFactory := &SMSNotificationFactory{}
	smsMessage := SendNotification(smsFactory, "Hello, SMS!")
	println(smsMessage)
}

// 出力
// Email: Hello, Email!
// SMS: Hello, SMS!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?