Home >Backend Development >Golang >System design: Building a Vending Machine in Go
Living in Tokyo, Japan, I’m surrounded by vending machines offering everything from hot coffee to cold drinks and snacks.Inspired by these iconic machines, I trued to build a vending machine system design in Go. It's a cool example of using the State pattern, and I'll break down why it's super useful for this kind of project.
Think about a real vending machine - it's actually pretty complex! It needs to:
Plus, it needs to do all this without getting confused about what state it's in.
First up, I needed some basic structures to work with:
Products and Inventory
Each product has an ID, name, price, and quantity. Pretty straightforward stuff:
type Product struct { ID int Name string Price float64 Quantity int }
The inventory keeps track of all products using a map. It can:
The State Pattern: Why It's Awesome Here
Here's where it gets interesting. A vending machine can be in different states:
Each state needs to handle user actions differently. Like, you can't select a product before putting in money, right?
I used three main states:
Each state implements this interface:
type State interface { InsertMoney(amount float64) SelectProduct(product *Product) ReturnChange() DispenseProduct() }
How It All Works Together
Let's say you want to buy a Coke:
First, you insert $2.00
You select Coke ($1.50)
Machine dispenses your Coke
Building this taught me a few things:
There's always room for improvement! Some ideas:
The full code is more detailed than what I showed here, but these are the main pieces that make it work. Feel free to check the full implementation in the following repo:
Welcome to the Low-Level System Design in Go repository! This repository contains various low-level system design problems and their solutions implemented in Go. The primary aim is to demonstrate the design and architecture of systems through practical examples.
Low-level system design involves understanding the core concepts of system architecture and designing scalable, maintainable, and efficient systems. This repository will try to cover solutions of various problems and scenarios using Go.
The first project in this repository is a Parking Lot System. This system simulates a parking lot where vehicles can be parked and unparked. It demonstrates:
The above is the detailed content of System design: Building a Vending Machine in Go. For more information, please follow other related articles on the PHP Chinese website!